控制流
If 相关
- 不把变量和
True False None () [] {}
等直接比较
比如
if foo == True:
应该写成
if foo:
- 检查变量在列表中
#错误
is_generic_name = False
name = 'Tom'
if name == 'Tom' or name == 'Dick' or name == 'Harry':
is_generic_name = True
而是
name = 'Tom'
is_generic_name = name in ('Tom', 'Dick', 'Harry')
- if不该写在一行
name = 'Jeff'
address = 'New York, NY'
if name: print(name)
print(address)
应该为:
name = 'Jeff'
address = 'New York, NY'
if name:
print(name)
print(address)
For 相关
- 须有index的场景用enumerate
my_container = ['Larry', 'Moe', 'Curly']
index = 0
for element in my_container:
print ('{} {}'.format(index, element))
index += 1
应为:
my_container = ['Larry', 'Moe', 'Curly']
for index, element in enumerate(my_container):
print ('{} {}'.format(index, element))
网友评论