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 a user were to enter a non-integer it would work as planned, however if they were to enter it again, it would just raise ValueError again and crash.
What is the best way to fix this?
Exception means error detection during execution. In this example, we can easily use the try-except block to execute the code. Try is basically the keyword that is used to keep the code segments While in the case of except it is the segment that is actually used to handle the exception.
The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error. The finally block lets you execute code, regardless of the result of the try- and except blocks.
Python Multiple ExceptsIt is possible to have multiple except blocks for one try block.
The try… except block is completed and the program will proceed. However, if an exception is raised in the try clause, Python will stop executing any more code in that clause, and pass the exception to the except clause to see if this particular error is handled there.
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.
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:~$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With