How to repeat try-except block

I have a try-except block in Python 3.3, and I want it to run indefinitely.

try: imp = int(input("Importance:\n\t1: High\n\t2: Normal\n\t3: Low")) except ValueError: imp = int(input("Please enter a number between 1 and 3:\n> ") 

Currently, if the user needs to enter a non-integer, he will work as planned, however, if he had to enter it again, he will simply raise a ValueError and fail again.

What is the best way to fix this?

+6
source share
2 answers

Put it inside the while loop and break out when you have the input you expect. It is probably best to save all imp dependent code in try , as shown below, or set it to its default value to prevent further NameError .

 while True: try: imp = int(input("Importance:\n\t1: High\n\t2: Normal\n\t3: Low")) # ... Do stuff dependant on "imp" break # Only triggered if input is valid... except ValueError: print("Error: Invalid number") 
+12
source
 prompt = "Importance:\n\t1: High\n\t2: Normal\n\t3: Low\n> " while True: try: imp = int(input(prompt)) if imp < 1 or imp > 3: raise ValueError break except ValueError: prompt = "Please enter a number between 1 and 3:\n> " 

Output:

 rob@rivertam :~$ python3 test.py Importance: 1: High 2: Normal 3: Low > 67 Please enter a number between 1 and 3: > test Please enter a number between 1 and 3: > 1 rob@rivertam :~$ 
+6
source

All Articles