简体   繁体   中英

How to accept only 5 possible inputs

In my program I have a menu that looks like this?:

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 ") 

I just want to know a way in which I can insure that only the numbers 1 to 5 are accepted and that if anything else is entered then the program asks the question again.

Please dont roast me.

Thanks

You're right to use a while loop, but think of what condition you want. You want only the numbers 1-5 right? So it would make sense to do:

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

We make our input an integer so that we can see if it's between 1-5. Also, you should put your beginning print statements outside of the loop so it doesn't continually spam the reader (unless this is what you want).

I think he needs a While true loop . Did using 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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