这是一个循环,允许用户从列表中仅选择一个项目。
types = ['Small', 'Medium','Large']
while True:
print('Types: '+ types)
choice = raw_input('Choose a type. ').capitalize()
if choice in types:
choice = choice
break
else:
choice = raw_input('Choose a type. ').capitalize()
我在想这个循环是否有更小更干净的版本。尝试除版本以外的其他版本。这是最好的书写方式吗?备择方案?
有任何想法吗?
几行是不必要的,我将对其进行评论:
types = ['Small', 'Medium','Large']
while True:
print('Types: '+ types)
choice = raw_input('Choose a type. ').capitalize()
if choice in types:
#choice = choice this is superfluos
break
#else: no need for else since the loop will execute again and do exactly this
# choice = raw_input('Choose a type. ').capitalize()
最终结果如下:
types = ['Small', 'Medium','Large']
while True:
print('Types: '+ types)
choice = raw_input('Choose a type. ').capitalize()
if choice in types:
break
注意:如果您不想Types
每次都重复,只需将其print
移出循环即可:
types = ['Small', 'Medium','Large']
print('Types: '+ types)
while True:
...
另外,您使用的代码raw_input()
或print()
使用括号的代码都与特定的Python版本不一致,但不能混合使用(除非您进行一些__future__
导入)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句