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\")
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:~$
Put it inside a while loop and break out when you've got the input you expect. It's probably best to keep all code dependant on imp
in the try
as below, or set a default value for it to prevent NameError
's further down.
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")
EDIT: user2678074 makes the valid point that this could make debugging difficult as it could get stuck in an infinite loop.
I would make two suggestions to resolve this - firstly use a for loop with a defined number of retries. Secondly, place the above in a function, so it's kept separate from the rest of your application logic and the error is isolated within the scope of that function:
def safeIntegerInput( num_retries = 3 ):
for attempt_no in range(num_retries):
try:
return int(input("Importance:\n\t1: High\n\t2: Normal\n\t3: Low"))
except ValueError as error:
if attempt_no < (num_retries - 1):
print("Error: Invalid number")
else:
raise error
With that in place, you can have a try/except outside of the function call and it'll only through if you go beyond the max number of retries.