Why is there a UnboundLocalError when raising an exception and using input()?

201 views Asked by At

When I ask for input and convert it to an integer using int(), and when you enter an integer it handles like no problem. However, when the user enters the wrong value it gives me two errors even though I have used exception handling. Here's the code:

def rand_num():
    try:
        print("Welcome to the random number generator!")
        print()
        rand_max = int(input("Enter the maximum number to randomly generate: "))
        print()
        print(f"Your random number is: {random.randint(0, rand_max)}")
    except:
        print(f"Sorry, {rand_max} is not an integer!")

And here are the errors:

Original exception was:
Traceback (most recent call last):
  File "py_cli_calc.py", line 17, in rand_num
    rand_max = int(input("Enter the maximum number to randomly generate: "))
ValueError: invalid literal for int() with base 10: 'str'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "py_cli_calc.py", line 23, in <module>
    rand_num()
  File "py_cli_calc.py", line 21, in rand_num
    print(f"Sorry, {rand_max} is not an integer!")
UnboundLocalError: local variable 'rand_max' referenced before assignment

I've tried placing different blocks of code in the try block, but I am so confused why the exception does not work like I intended to (it's supposed to except a ValueError if the user types the wrong type in. Also, I am confused why I am getting an UnboundLocalError, because isn't my rand_max variable accessible by the except? I have tried rearranging the code in different ways, such as placing the variable that raises an error outside of the try, but I still receive an UnboundLocalError! I'm so confused about this, so please help me!

2

There are 2 answers

0
kederrac On BEST ANSWER

if you look at your previous error(ValueError: invalid literal for int() with base 10: 'str'), your rand_max variable it doesn't get assigned, this causes the last error:

UnboundLocalError: local variable 'rand_max' referenced before assignment
0
pykeegan3306 On

Update: I fixed it! Here is the code:

def rand_num():
    print("Welcome to the random number generator!")
    while True:
        print()
        rand_max = input("Enter the maximum number to randomly generate: ")
        try:
            if rand_max == "quit" or rand_max == "exit":
                print("Thanks for using the random number generator!")
                break
            else:
                print()
                print(f"Your random number is: {random.randint(0, int(rand_max))}")
        except ValueError:
            print(f"Sorry, {rand_max} is not an integer!")

I reassigned rand_max to a regular string input() but then I convert the input in the try block using int() if the input does not equal "quit" or "exit". Then I use except ValueError to print an error message if the try block found that the input entered is not of the int type, and it worked. Thank you for helping me, especially with the UnboundLocalError, because that really baffled me!