简体   繁体   中英

Unbound Local Error: local variable referenced before assignment inside of a try and except statement

I am attempting to create a very simple menu system, using all of the pythonic tools, (try and except statements, loops, if statements) and I have run into a little bit of trouble.

This is the code and error message i have at the moment

def Menu():
while True:
    print("""
    Hello, please enter a number 1 - 4
        1 - Compliment
        2 - Fact
        3 - Insult
        4 - Quit
        """)

    try:
        UserInput_INT = int(input("> "))


    except ValueError:
        UserInput_STR = (UserInput_INT)
        if len(UserInput_STR) == 0:
            print("You have entered nothing. Please enter a number between 1 and 4")
        print("You entered a character. Please enter a number between 1 and 4")
        Menu()

    if  UserInput_INT not in range (1, 5):
        print("Invalid input please enter a whole number between 1 and 4")
        continue

    UserInput_STR = (str(UserInput_INT))
    if UserInput_STR == '1':
        print(" You look horrible today!")

    elif UserInput_STR == '2':
        print("Sam Birkenshaw & Jordan Ives can code better than Mr Bath. ")

    elif UserInput_STR == '3':
        print("You are bad at coding ")

    elif UserInput_STR == '4':
        quit()

Menu()

error message:

"Traceback (most recent call last): File "E:/All/School Work/Computer Science/Code/SAM broken code.py", line 12, in Menu UserInput_INT = int(input("> ")) ValueError: invalid literal for int() with base 10: ''

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "E:/All/School Work/Computer Science/Code/SAM broken code.py", line 39, in Menu() File "E:/All/School Work/Computer Science/Code/SAM broken code.py", line 16, in Menu UserInput_STR = (UserInput_INT) UnboundLocalError: local variable 'UserInput_INT' referenced before assignment"

I need to have it so that if the user enters nothing, there is a different message displayed than if they enter a letter, and if they enter something other than one of the accepted answers.

(I am runing python 3.6.2 currently)

The value that is being passed as input to the program is not a valid integer. Now, when an exception is raised the variable UserInput_INT is not being assigned causing the second error. Try checking if the value is integer before trying to cast it.

input = input("> ")
UserInput_INT = int(input) if input.isdigit() else input

As a side note, please try to follow naming conventions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM