程序员

Python好习惯(1)

2018-04-20  本文已影响20人  WilliamY

控制流

If 相关

#错误
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')
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 相关

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))
上一篇下一篇

猜你喜欢

热点阅读