繁体   English   中英

Unbound Local Error:在try和except语句内进行赋值之前引用的局部变量

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

我试图使用所有pythonic工具(尝试和除语句,循环,if语句)创建一个非常简单的菜单系统,但遇到了一些麻烦。

这是我目前的代码和错误消息

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

菜单()

错误信息:

“跟踪(最近一次通话最近):文件“ E:/ All /学校/计算机科学/代码/ SAM损坏的code.py”,菜单UserInput_INT = int(input(“>”)))第12行,ValueError:无效以10为底的int()的文字:''

在处理上述异常期间,发生了另一个异常:

追溯(最近一次通话):文件“ E:/ All /学校/计算机科学/代码/ SAM损坏的code.py”,第39行,位于Menu()文件“ E:/ All /学校/计算机科学/ “代码/ SAM损坏的code.py”,菜单UserInput_STR =(UserInput_INT)中的第16行,UnboundLocalError:分配前引用了本地变量“ UserInput_INT”

我需要它,以便如果用户不输入任何内容,则显示的消息不同于他们输入字母以及输入的字符不是接受的答案之一。

(我目前正在运行python 3.6.2)

作为输入传递给程序的值不是有效的整数。 现在,当引发异常时,未分配变量UserInput_INT导致第二个错误。 尝试在转换前将值检查是否为整数。

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

作为旁注,请尝试遵循命名约定。

暂无
暂无

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

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