作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要再次询问选择,直到用户选择有效的选项。
choice = input('Please choose 1,2,3\n')
if choice == 1:
print('You have chosen the first option')
elif choice == 2:
print('You have chosen the second option')
elif choice == 3:
print('You have chosen the third option')
else:
print('This is not an option, please try again.')
最佳答案
也许我错了,因为我只是一个黑客,但我相信一个更“Pythonic”的答案是:
choices = {1:'first', 2:'second', 3:'third'}
while True:
choice = input('Please choose 1, 2, or 3.\n')
try:
print 'You have chosen the {} option.'.format(choices[choice])
break
except KeyError:
print 'This is not an option; please try again.'
或者至少:
while True:
choice = input('Please choose 1, 2, or 3.\n')
if choice == 1:
print 'You have chosen the first option'
break
elif choice == 2:
print 'You have chosen the second option'
break
elif choice == 3:
print 'You have chosen the third option'
break
else:
print 'This is not an option; please try again.'
这两者都避免创建不必要的测试变量,第一个减少了所需的总体代码。
对于 Python 3,我相信在打印语句周围添加括号应该是唯一的变化。该问题未标记版本。
关于python - 如果Python中输入无效,如何让程序再次提示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31797863/
我是一名优秀的程序员,十分优秀!