Python在定义变量时给出未绑定错误

pod7payv  于 2023-05-21  发布在  Python
关注(0)|答案(1)|浏览(110)

你好,我有一个错误,这是告诉我变量定义,但它的定义行以上
我做错了什么?
我的代码:

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

错误信息:

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

我到底做错了什么?

b1payxdu

b1payxdu1#

因为mp004的减速在if语句中,这可能会导致应用程序在没有首先声明它的情况下到达它正在使用的行。您需要处理data不在任何i中的方式

相关问题