如何只接受5种可能的输入

时间:2016-10-16 10:58:01

标签: python error-handling menu

在我的程序中,我有一个如下所示的菜单:

MenuChoice = ''
while MenuChoice != 'x':
print("Type 1 to enter the first option")
print("Type 2 to enter the second option")
print("Type 3 to enter the third option")
print("Type 4 to enter the fourth option")
print("Press x to quit")
try: 
    MenuChoice = str(input("Please enter your choice here ----------------->>>>>")) 
except ValueError: 
    print("Please enter one of the menu choices above, TRY AGAIN ") 

我只是想知道一种方法,我可以确保只接受数字1到5,如果输入了其他内容,那么程序会再次询问问题。

请不要烤我。

由于

2 个答案:

答案 0 :(得分:1)

您使用while循环是正确的,但请考虑您想要的条件。你只想要数字1-5吗?所以这样做是有道理的:

MenuChoice = 0
print("Type 1 to enter the first option")
print("Type 2 to enter the second option")
print("Type 3 to enter the third option")
print("Type 4 to enter the fourth option")
print("Press x to quit")
while not (1 <= MenuChoice <= 4):
    MenuChoice = input("Please enter your choice here ----------------->>>>>")
    if MenuChoice == 'x' : break
    try:
        MenuChoice = int(MenuChoice)
    except ValueError:
        print("Please enter one of the menu choices above, TRY AGAIN ") 
        MenuChoice = 0 # We need this in case MenuChoice is a string, so we need to default it back to 0 for the conditional to work

我们输入一个整数,以便我们可以看到它是否在1-5之间。此外,您应该将您的开始打印语句放在循环之外,这样它就不会不断地向读者发送垃圾邮件(除非这是您想要的)。

答案 1 :(得分:0)

我认为他需要一个真正的循环。使用python 2.X

import time
print("Type 1 to enter the first option")
print("Type 2 to enter the second option")
print("Type 3 to enter the third option")
print("Type 4 to enter the fourth option")
print("Press x to quit")

while True:
    try:
        print ("Only Use number 1 to 4 or x to Quit... Thanks please try again")
        MenuChoice = raw_input("Please enter your choice here ----------------->>>>> ")
        try:
            MenuChoice = int(MenuChoice)
        except:
            MenuChoice1 = str(MenuChoice)
        if MenuChoice1 == 'x' or 1 <= MenuChoice <= 4:
            print "You selected %r Option.. Thank you & good bye"%(MenuChoice)
            time.sleep(2)
            break
    except:
        pass