Make a function to ask for integers, floats, etc...
You can catch this Exception and continue.
The else-block returns the value. In the case a ValueError happens, the else-block is not executed.
The function will not return the value and ask the user again for input.
from functools import partial def ask(question, dtype=str, error_msg=None): while True: user_input = input(question) try: value = dtype(user_input) except ValueError: if error_msg: print(error_msg) else: return value ask_int = partial(ask, dtype=int, error_msg="Please enter a valid integer.") ask_float = partial(ask, dtype=float, error_msg="Please enter a valid float.") ask_complex = partial(ask, dtype=complex, error_msg="Please enter a valid complex")
ask_int("How old are you? ")
Output:In [26]: ask_int("How old are you? ")
How old are you? 128
Out[26]: 128
In [27]: ask_int("How old are you? ")
How old are you? 12.5
Please enter a valid integer.
How old are you? aaaaaa
Please enter a valid integer.
Just try following in the repl:int("AAA")You'll get a:
Error:In [28]: int("AAA")
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-28-ac34db391e65> in <module>
----> 1 int("AAA")
ValueError: invalid literal for int() with base 10: 'AAA'
An illegal value for int raises the ValueError
.You can catch this Exception and continue.
try: value = int(input("Value: ")) except ValueError: print("Wrong value") else: # all fine, no exception at all print(value)Finally, I put this block in a while-True loop and the while-True loop in a function.
The else-block returns the value. In the case a ValueError happens, the else-block is not executed.
The function will not return the value and ask the user again for input.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!