简体   繁体   English

Python错误-UnboundLocalError:分配前引用了局部变量

[英]Python Error - UnboundLocalError: local variable referenced before assignment

My issue: In my program I have a function which is only supposed to run when the user has inputed several values which are then kept in a dictionary. 我的问题:在我的程序中,我有一个只能在用户输入几个值后才运行的函数,然后将这些值保存在字典中。 My initial idea was in the function to get the length of the dictionary and if it was 0 (meaning it was empty) that would be a sign the values haven't been inputed. 我最初的想法是在函数中获取字典的长度,如果该长度为0(表示为空),则表明没有输入值。 However when I run the code I get this error 'UnboundLocalError: local variable 'dictionary' referenced before assignment'. 但是,当我运行代码时,出现此错误“ UnboundLocalError:分配前引用的本地变量” dictionary”。 On the other hand though when length is more than 1 (the values have been entered) the code runs perfectly. 另一方面,尽管当length大于1(已输入值)时,代码可以完美运行。 The relevant code is as follows; 相关代码如下;

def displayValues(data):
    if len(data) == 0:
        print('No Values Found - Please Enter Values')
        Main()
    elif len(data) != 0:
        print()
        print('-'*77)
        for key,value in sorted(data.items()):
            print(key,':',value)
            print('-'*77)
        time.sleep(5)
        print()

def Main():
    while True:
        choice = displayMenu()
        if choice == 1:
            dictionary = setValues()
        elif choice == 2:
            displayValues(dictionary)
        elif choice == 3:
            runModel(dictionary)
        elif choice == 4:
            exportData()
        elif choice == 5:
            quit()

Main()

Please note I am sure the setValues() function which returns the values saved in the dictionary variable is functioning as if the case is that the len of the dictionary is not 0 the code works fine. 请注意,我确定返回字典变量中保存的值的setValues()函数的功能就像在字典的len不为0的情况下一样,可以正常工作。 Also I have not used the variable name 'dictionary' anywhere else in the code therefore it is not being repeated. 另外,我在代码中的其他任何地方都没有使用变量名'dictionary',因此不会重复使用。 Any possible ideas of where I am going wrong would be appreciated? 关于我要去哪里的任何可能的想法将不胜感激? Thanks 谢谢

Initialize dictionary to be an empty dict ( {} ) before working with it. 在使用字典之前,将其初始化为空字典( {} )。 Then you can do if dict to check whether it contains any data. 然后, if dict可以检查它是否包含任何数据。 That way you are assured that dictionary has a value any time after the initialization. 这样,您可以确保dictionary在初始化后的任何时间都有一个值。

def Main():
    dictionary = {}
    while True:

you need to declare (and define) your dictionary before using it, as if you hit 2 or 3 you'll try to access a variable that has not been declared yet. 您需要在使用字典之前声明(并定义)字典,就像您按2或3一样,您将尝试访问尚未声明的变量。

Then, when you'll hit 2 or 3, it'll behave for an empty dict, and when you'll hit 1 it'll behave the way you want. 然后,当您按下2或3时,它将表现为空字典,而当您按下1时,它将按照您想要的方式表现。

def Main():
    dictionary = {}
    while True:
        choice = displayMenu()
        if choice == 1:
            dictionary = setValues()
        elif choice == 2:
            displayValues(dictionary)
        elif choice == 3:
            runModel(dictionary)
        elif choice == 4:
            exportData()
        elif choice == 5:
            quit()

空字典在Python中的计算结果为False,因此将'if len(data)== 0'更改为'if not data'应该可以解决您的问题。

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

相关问题 UnBoundLocalError:赋值之前引用的局部变量(Python) - UnBoundLocalError: local variable referenced before assignment (Python) python - UnboundLocalError:分配前引用的局部变量 - python - UnboundLocalError: local variable referenced before assignment Python-UnboundLocalError:分配前引用的局部变量 - Python - UnboundLocalError: local variable referenced before assignment` Python UnboundLocalError:分配前引用了局部变量 - Python UnboundLocalError: local variable referenced before assignment UnboundLocalError:赋值前引用的局部变量'error' - UnboundLocalError: local variable 'error' referenced before assignment UnboundLocalError: 赋值前引用的局部变量错误 - UnboundLocalError: local variable referenced before assignment error Python 错误:UnboundLocalError:赋值前引用了局部变量“score1” - Python error: UnboundLocalError: local variable 'score1' referenced before assignment Python错误:UnboundLocalError:赋值前引用的局部变量'f' - Python Error :UnboundLocalError: local variable 'f' referenced before assignment Python | 如果变量:| UnboundLocalError:赋值前引用的局部变量'variable' - Python | if variable: | UnboundLocalError: local variable 'variable' referenced before assignment 错误-UnboundLocalError:分配前已引用本地变量“ VARIABLE_NAME” - Error - UnboundLocalError: local variable 'VARIABLE_NAME' referenced before assignment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM