繁体   English   中英

如果输入在Python中无效,如何再次显示程序提示?

[英]How can you make a program prompt again if the input is invalid in Python?

在用户选择有效选项之前,我需要再次询问选择。

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,我相信唯一的更改应该是在打印的语句周围加上括号。 这个问题没有标注版本。

尝试这个:

valid = False
while(valid == False):

   choice = input("Please choose 1,2,3\n")

   if choice == 1:
      valid = True
      print('You have chosen the first option')

   elif choice == 2:
     valid = True
     print('You have chosen the second option')

   elif choice == 3:
     valid = True
     print('You have chosen the third option')

   else:
     valid = False
     print('This is not an option, please try again.')

您可以将其设置为一个函数,该函数接受所需的提示,有效的选择,并且仅在进行有效输入时才返回。

def get_input(prompt, choices):
    while True:
        choice = input("%s %s or %s: " % (prompt, ", ".join(choices[:-1]), choices[-1]))
        if str(choice) in choices:
            return choice

choice = get_input("Please choose", ["1", "2", "3"])
print("You have chosen {}".format(choice))

这将提供以下类型的输出:

Please choose 1, 2 or 3: 1
You have chosen 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM