user6361496
user6361496

Reputation:

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. However when I run the code I get this error 'UnboundLocalError: local variable 'dictionary' referenced before assignment'. On the other hand though when length is more than 1 (the values have been entered) the code runs perfectly. 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. Also I have not used the variable name 'dictionary' anywhere else in the code therefore it is not being repeated. Any possible ideas of where I am going wrong would be appreciated? Thanks

Upvotes: 1

Views: 8040

Answers (3)

zmo
zmo

Reputation: 24812

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.

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.

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

Upvotes: 1

handris
handris

Reputation: 2109

Empty dictionaries evaluate to False in Python, so chaning 'if len(data) == 0' to 'if not data' should solve your problem.

Upvotes: -1

Srikanth
Srikanth

Reputation: 1003

Initialize dictionary to be an empty dict ({}) before working with it. Then you can do if dict to check whether it contains any data. That way you are assured that dictionary has a value any time after the initialization.

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

Upvotes: 2

Related Questions