gpt4 book ai didi

python - 如果Python中输入无效,如何让程序再次提示?

转载 作者:行者123 更新时间:2023-12-01 04:35:19 24 4
gpt4 key购买 nike

我需要再次询问选择,直到用户选择有效的选项。

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com