Writing an input validation loop in Python

I’m trying to code an input validation loop for the difficuilty selection of a game…

while True:
diffChoice = input("Select a difficuilty...n[e]asy, [m]edium, [h]ard: ").lower()

if diffChoice in ('e', 'm', 'h', 1, 2, 3):
    break
else:
    diffChoice = input("Incorrect input...nSelect a difficuilty...n[e]asy, [m]edium, [h]ard: ").lower()

The problem is that when I enter an incorrect input it correctly prints the error however when I then enter the correct input the loop goes back to the start and asks for input again.

Any advice welcomed or if you know a better way to write this validation loop, please let me know!

Thanks in advance 🙂

Answer

while True:
    diffChoice = input("Select a difficuilty...n[e]asy, [m]edium, [h]ard: ").lower()

    if diffChoice in ('e', 'm', 'h', 1, 2, 3):
        break
    else:
        diffChoice = input("Incorrect input...nSelect a difficuilty...n[e]asy, [m]edium, [h]ard: ").lower()

The while True causes loop to run forever and since you have break statement inside the if condition only, it’s likely that always the else part is getting executed.. notice your if condition diffChoice in ('e', 'm', 'h', 1, 2, 3), 1,2,3 are integers however they are always going to be read as character/string because you are not performing any type conversion.. You should consider changing the if conditional to use integer values as characters/strings..

diffChoice in ('e', 'm', 'h', '1', '2', '3')

Another thing I noticed is, you are asking for input in the else part also, so when you enter wrong answer once, you go to else part and it asks for input and since there is no condition inside the else part any further, the loop again continues, and it starts asking for the input again.. So for wrong answer, you are asking for the input twice.. After fixing these issues, your code should be something similar to:

while True:
    diffChoice = input("Select a difficuilty...n[e]asy, [m]edium, [h]ard: ").lower()

    if diffChoice in ('e', 'm', 'h', '1', '2', '3'):
        break
    else:
        print("Incorrect input...n")

Leave a Reply

Your email address will not be published. Required fields are marked *