简体   繁体   English

UnboundLocalError: TRY EXCEPT STATEMENTS

[英]UnboundLocalError: TRY EXCEPT STATEMENTS

I am currently creating a menu with try except tools.我目前正在使用try except工具try except创建菜单。 I'm trying to create it so if a user enters nothing (presses ENTER) to output:我正在尝试创建它,因此如果用户不输入任何内容(按 ENTER)以输出:

You have not entered anything, please enter a number between 1 and 4您尚未输入任何内容,请输入 1 到 4 之间的数字

这是错误信息(点击这里)

This is what I've done so far:这是我到目前为止所做的:

def Menu():
    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")


    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()

Try this and its same as you expected your output to be.试试这个,它和你期望的输出一样。

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

So here we first input into UserInput_INT and then in the try block we cast it to integer type.所以在这里我们首先输入 UserInput_INT 然后在 try 块中我们将它转​​换为整数类型。

In the statement UserInput_STR = (UserInput_INT) [*] you are accessing a variable that you did not initalize, since int(input("> ")) have failed.UserInput_STR = (UserInput_INT) [*] 语句中,您正在访问一个未初始化的变量,因为int(input("> "))已失败。 Here's a shorter example:这是一个较短的示例:

def f():
    try:
        x = 2/0
    except:
        print(x)

What should print(x) do? print(x)应该做什么? the variable is indeed local, but is not bound.该变量确实是局部的,但不受约束。 It is not initialized.它没有被初始化。

[*] I believe you meant something like UserInput_STR = str(UserInput_INT) , but it won't work either for the same reason. [*] 我相信你的意思是像UserInput_STR = str(UserInput_INT) ,但由于同样的原因它也不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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