0

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

1 Answers1

0

Move the try-except into a loop. It will continue to run until a valid value is entered and it returns.

def get_user_choice():
    while True:
        try:
            user_choice = int(input("Choice: "))
            return user_choice
        except ValueError:
            print("\nERROR: Please enter a valid integer value. Retrying...\n")
            time.sleep(0.5)
            show_menu()

user_input = get_user_choice()

You could also use recursion:

def get_user_choice():
    try:
        return int(input("Choice: "))
    except ValueError:
        print("\nERROR: Please enter a valid integer value. Retrying...\n")
        time.sleep(0.5)
        show_menu()
        return get_user_choice()

The problem in your modified code is that you are not returning the value.

Jon Zavialov
  • 231
  • 1
  • 10