英文:
Python gives unbound error when variable is defined
问题
你好,你的代码中出现了一个错误。错误信息显示 "UnboundLocalError: local variable 'mp004' referenced before assignment",这意味着在 get_database
函数中尝试访问变量 'mp004' 之前未进行赋值操作。这可能是由于在循环中没有匹配到 data
所导致的。你可以考虑在循环结束后,如果没有找到匹配的数据,为 'mp004' 分配一个默认值,以避免这个错误。例如:
def get_database(data, database, database1):
mp004 = -1 # 默认值,如果没有匹配项
for c, i in enumerate(database):
if data in i:
mp004 = c
return database1[mp004]
这样,如果没有找到匹配项,'mp004' 将保持为默认值 -1,而不会引发 "UnboundLocalError" 错误。
英文:
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?
答案1
得分: 1
因为 mp004
的减速在 if
语句中,这可能会导致应用在未先声明它的情况下使用它的那一行。
你需要处理 data
不在任何 i
中的方式。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论