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

>Solution :

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

as a side note, for those valid values, float should probably be int as any floating point value would be rejected anyway unless the decimal part is .0

Leave a Reply