-1

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")
saZ
  • 89
  • 7

2 Answers2

0

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

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

Maybe create a function to take input:

def get_input():
    while True:
        a = input("Pick a number: ")
        try:
            return float(a)
        except:
            pass
Pedro Maia
  • 2,666
  • 1
  • 5
  • 20