Home > Enterprise >  How do I validate user input while catching other data types?
How do I validate user input while catching other data types?

Time:03-10

Trying to validate user input in my program.

 playerChoice = int(input("Enter your choice: "))
    

while playerChoice != 1 and playerChoice != 2 and playerChoice != 3 and playerChoice !=4:
    print("Please make a valid selection from the menu.")
    playerChoice = int(input("Enter your choice: "))

This works great as long as the input is an integer (the problem statement specifically states the input is an integer). However, if I enter 1.5 or xyz, I get an unhandled ValueError exception.

So I changed it:

try:
    playerChoice = int(input("Enter your choice: "))
    
    while playerChoice not in(1, 2, 3, 4):
        print("Please make a valid selection from the menu.")
        playerChoice = int(input("Enter your choice: "))
                   
except ValueError:
    print("Please enter a number.")
    playerChoice = int(input("Enter your choice: "))

which also works great...once. I know the solution here is simple but I can't figure out how to get the code into a loop that will handle other data types. What am I missing?

Sorry for asking such a dumb question.

CodePudding user response:

Put the try/except inside your loop:

while True:
    try:
        playerChoice = int(input("Enter your choice: "))
        if playerChoice not in (1, 2, 3, 4):
            print("Please make a valid selection from the menu.")
        else:
            break
    except ValueError:
        print("Please enter a number.")

CodePudding user response:

Put a while loop around the whole thing.

while True:
    try:
        playerChoice = int(input("Enter your choice: "))
        
        if playerChoice in(1, 2, 3, 4):
            break
            
        print("Please make a valid selection from the menu.")
                       
    except ValueError:
        print("Please enter a number.")

Notice that by putting the input() call inside the main loop, you only have to write it once, rather than repeating it after all the validation checks.

CodePudding user response:

It is because you put the try ... except clause outside of the loop, while you want it to be inside of it.

playerChoice = None
while not playerChoice:
    try:
        playerChoice = int(input("Enter your choice: "))
        if playerChoice not in(1, 2, 3, 4) :
            print("Please make a valid selection from the menu.")
            playerChoice = None
    except ValueError:
        print("Please enter a number.")
  • Related