Search code examples
pythonvalidationuser-input

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


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.


Solution

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