Python 从列表中选择的最佳方式
这是一个循环,允许用户仅从列表中选择一项Python 从列表中选择的最佳方式,python,list,loops,Python,List,Loops,这是一个循环,允许用户仅从列表中选择一项 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
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']
print('Types: '+ types)
while True:
choice = raw_input('Choose a type. ').capitalize()
if choice in types:
break
有几行是不必要的,我将向他们展示:
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 = ['Small', 'Medium','Large']
print('Types: '+ types)
while True:
...
另外,您的代码与特定的Python版本不一致,或者您使用带括号的
raw\u input()
或print()
,但不能混合使用(除非您执行一些\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu未来导入)。什么Python版本?第二个版本中,您似乎混合了3和2(print()和raw_输入)。我习惯使用第三版的print()。明白了,这可能会产生误导:)您应该删除代码的最后两行。