Search code examples
pythonvariablesunbound

Python gives unbound error when variable is defined


Hello I have an error which is telling me variable defined but it's defined line above
What did I do wrong?
My code:

a = open("dialogs/dialogs.txt").read().splitlines()
def parse(string):
    string = string.lower().split()
    s1 = ""
    for l in string:
        s1+=l[0]
    return s1
def get_database(data,database,database1):
    for c,i in enumerate(database):
        if data in i:
            mp004 = c
    return database1[mp004]

ques = []
anws = []
for c,i in enumerate(a):
    try:
        m = i.split("\t")
        ques.append(parse(m[0]))
        anws.append(m[1])
    except:
        pass
    print(f"Trained {c}/{len(a)-1}            ",end="\r")
    
print()
while True:
    p = input("> ")
    print(get_database(p,ques,anws))

Error message:

Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
    start(fakepyfile,mainpyfile)
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
    exec(open(mainpyfile).read(),  __main__.__dict__)
  File "<string>", line 28, in <module>
  File "<string>", line 12, in get_database
UnboundLocalError: local variable 'mp004' referenced before assignment

What did I do actually wrong?


Solution

  • Because the deceleration of mp004 is in the if statement, this might cause the application to get to the line it is being used without declaring it first. You need to handle the way data is not in any i