Python:UnboundLocalError:赋值前引用的局部变量'count'

Yoh*_*oth 2 python

我无法理解我的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
Run Code Online (Sandbox Code Playgroud)

这是代码的一部分

我定义了全局变量

count = 3
Run Code Online (Sandbox Code Playgroud)

然后我创建了方法main

def main():
    f = open(filename, 'r')

    if f != None:
        for line in f:

            #some code here

            count -= 1
            if count == 0: 
                break
Run Code Online (Sandbox Code Playgroud)

这可能有什么问题?

谢谢

Mat*_*t S 5

count -= 1相当于count = count - 1. count在本地定义之前正在进行评估.当发生这种情况时,您需要将count函数内的范围显式设置为全局(即在函数外部定义).

def main():
    global count
Run Code Online (Sandbox Code Playgroud)