I am currently making a calculator application with a menu. When an invalid input (eg. String) is entered, the ValueError
exception is thrown.
I have a try-except
block to catch the exception. However, it will only catch it one time. If I do the exact same input after, the ValueError
exception is thrown and it's not caught.
Code I have
Original
def get_user_choice():
try:
user_choice = int(input("Choice: "))
except ValueError:
print("\nERROR: Please enter a valid integer value. Retrying...\n")
time.sleep(0.5)
show_menu()
user_choice = int(input("Choice: "))
pass
Modified
If I put the get_user_choice()
function in the except
instead of asking for user_choice
, it throws an UnboundLocalError
.
try:
user_choice = int(input("Choice: "))
except (ValueError, UnboundLocalError):
print("\nERROR: Please enter a valid integer value. Retrying...\n")
time.sleep(0.5)
show_menu()
get_user_choice()
pass