Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading