【发布时间】:2016-04-19 13:58:16
【问题描述】:
我不明白我的 Python 代码有什么问题。它给了我以下错误:
Traceback (most recent call last):
File "main.py", line 77, in <module>
main();
File "main.py", line 67, in main
count -= 1
UnboundLocalError: local variable 'count' referenced before assignment
这是部分代码
我定义了全局变量
count = 3
然后我创建了方法 main
def main():
f = open(filename, 'r')
if f != None:
for line in f:
#some code here
count -= 1
if count == 0:
break
这里可能有什么问题?
谢谢
【问题讨论】:
-
你忘了告诉
main()count是全球性的。 -
(在主函数第一行添加
global count) -
最好的方法是跳过使用全局变量,而是使用函数参数和返回值。见:Why are global variables evil?
标签: python