Skip to content
Advertisement

Avoid ValueError outside a while loop?

In the second line, I am trying to make it not crash if a string is entered but can’t find a way to use an exception or something similar. In the while loop it works normally as the exception deals with this case.

number = 0 #this to be removed
number = (float(input('pick a number'))) #I want to make this not crash if a string is entered.
while number not in [100, 200, 3232]:
    try:
        print('wrong number ')
        number = (float(input('pick a number;'))) #Here it does not crash if a string is entered which is fine
    except ValueError:
        print("retry")

Advertisement

Answer

while followed by a variable condition often ends up with bugs/repeating code => bad maintenability.

Use a while True condition to avoid repeating your code, then break out the loop when it’s valid.

while True:
    try:
        number = float(input('pick a number;'))
        if number in [100, 200, 3232]:
           break
        print("wrong number")
    except ValueError:
        print("illegal number, retry")

note: be careful with float equality in the general case (see also strange output in comparison of float with float literal, Is floating point math broken?)

Advertisement