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

时间:2015-08-03 22:36:10

标签: 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.')

3 个答案:

答案 0 :(得分:2)

也许我错了,因为我只是一个黑客,但我相信更“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,我认为在打印语句周围添加括号应该是唯一的变化。问题没有用版本标记。

答案 1 :(得分:0)

试试这个:

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.')

答案 2 :(得分:0)

你可以将它变成一个函数,它接受所需的提示,有效的选择,只有在有效输入时返回。

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