从列表中选择的最佳方法

不速之客

这是一个循环,允许用户从列表中仅选择一个项目。

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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章