【问题标题】:UnboundLocalError: TRY EXCEPT STATEMENTSUnboundLocalError:尝试例外语句
【发布时间】:2017-10-03 21:24:30
【问题描述】:

我目前正在使用try except 工具创建一个菜单。我正在尝试创建它,因此如果用户不输入任何内容(按 ENTER)输出:

您还没有输入任何内容,请输入一个介于 1 和 4 之间的数字

这是我到目前为止所做的:

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

【问题讨论】:

标签: python python-3.x


【解决方案1】:

在语句UserInput_STR = (UserInput_INT) [*] 中,您正在访问一个未初始化的变量,因为int(input("> ")) 失败了。这是一个较短的示例:

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

print(x) 应该怎么做?该变量确实是本地的,但没有绑定。它没有被初始化。

[*] 我相信您的意思是 UserInput_STR = str(UserInput_INT),但出于同样的原因,它也不起作用。

【讨论】:

    【解决方案2】:

    试试这个,它和你期望的输出一样。

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

    所以这里我们首先输入到 UserInput_INT,然后在 try 块中我们将其转换为整数类型。

    【讨论】:

    • 您已经添加了一行并复制了他们的整个程序。相反,请提供该行,可能是围绕上下文的几行,以及解决问题的原因。见How to Answer
    • 它仍然说我需要在 try 语句之外定义 UserInput_INT。
    • @Sam.Birkenshaw - 不一定。只是不要在except 子句中使用它。而且你不需要它,因为它没有意义。
    • 但是我需要把它转换成一个字符串才能找到它的长度
    • 输入以字符串开头,因此您可以找到它的长度。
    猜你喜欢
    • 2016-10-02
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    • 2015-09-13
    • 1970-01-01
    相关资源
    最近更新 更多