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

pykeegan3306 :

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!

kederrac :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=346626&siteId=1