gpt4 book ai didi

python - 变量初始化时收到 "UnboundLocalError: local variable ' e'赋值前引用"

转载 作者:太空宇宙 更新时间:2023-11-03 12:21:37 35 4
gpt4 key购买 nike

<分区>

[社区编辑以提供可重现的示例:]

def main():
e = None
print(locals())
while not e:
try:
raise Exception
except Exception as e:
pass

main()

产生

~/coding$ python3.3 quiz2.py
{'e': None}
Traceback (most recent call last):
File "quiz2.py", line 11, in <module>
main()
File "quiz2.py", line 5, in main
while not e:
UnboundLocalError: local variable 'e' referenced before assignment

[已编辑] 包含可重现的代码

我正在尝试运行一个 while 循环,我使用的条件是当变量 e==None 时循环继续。相关代码如下:

    print("\nThe current score list contains the following people's scores: ")
score_list = open("score_list.dat", "rb")
score_name = []
e = None
while not e:
try:
score = pickle.load(score_list)
name = pickle.load(score_list)
score_name.append([score, name])
except EOFError as e:
pass
score_list_sorted=sorted(score_list)
sort_list.close()
for item in score_list_sorted:
print("Score: ", item[0], "\t", item[1])

完整代码在这里:https://www.dropbox.com/s/llj5xwexzfsoppv/stats_quiz_feb24_2013.py

它所需的数据文件(用于运行测验)位于此链接中:https://www.dropbox.com/s/70pbcb80kss2k9e/stats_quiz.dat

main() 需要编辑以使用正确的数据文件地址:

我收到的完整错误消息如下。这很奇怪,因为我在 while 循环之前初始化了 e。我希望有人能帮我解决这个问题。谢谢!

Traceback (most recent call last):
File "<pyshell#217>", line 1, in <module>
main()
File "/Users/Dropbox/folder/stats_quiz_feb24_2013.py", line 83, in main
while not e:
UnboundLocalError: local variable 'e' referenced before assignment

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com