+ 1

How can i ask for a valid input if the user does a wrong input?

Value= input('what do you prefer 'a' or 'b'? : ') I am trying to ask an user to input 'a' or 'b', but how can repeat the input question if he does a wrong input like 'c' , 'd', 1 or 2 etc whatever... To elaborate: If i run the code, >>> What do you prefer 'a' or 'b'?: c #if I don't raise an exception here the value becomes "value='c'". Which i don't want..instead i want to ask the user to again input the correct value like, >>>The value was incorrect enter again? :

27th Jul 2019, 11:07 AM
Amit Dubey
Amit Dubey - avatar
5 Réponses
+ 1
I tried this: While True: value= input().upper() If value!='a' and value!='b': Continue else: Break Print(value) #just to check And its asking me to enter value even after i enter 'a' or 'b' What's the problem mahnnn..
27th Jul 2019, 11:37 AM
Amit Dubey
Amit Dubey - avatar
+ 7
You need used 'and' instead 'or'
27th Jul 2019, 11:43 AM
Mikhail Gorchanyuk
Mikhail Gorchanyuk - avatar
+ 5
If an exception pops up, then you need to use 'try' and 'except' if there are no exceptions, you can create a condition 'if', 'elif' and 'else'
27th Jul 2019, 11:17 AM
Mikhail Gorchanyuk
Mikhail Gorchanyuk - avatar
+ 4
You could try a "while True" loop and check input. if input is ok, you leave while loop with break and go on with the program. while True: inp = input('please select "a" or "b"') if inp in 'ab': break print('invalid input - try again') print(f'input was {inp}')
27th Jul 2019, 11:21 AM
Lothar
Lothar - avatar
0
Now that was silly one from me, 😂 Anyways, thanks a lot💯
27th Jul 2019, 11:45 AM
Amit Dubey
Amit Dubey - avatar