在用户选择有效选项之前,我需要再次询问选择。
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/