简体   繁体   中英

Python: UnboundLocalError: local variable 'count' referenced before assignment

I cannot understand what is the problem in my Python code. It gives me the following error:

    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

Here is part of the code

I defined global variable

count = 3

then I created method main

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

    if f != None:
        for line in f:

            #some code here

            count -= 1
            if count == 0: 
                break

what may be wrong here?

Thanks

count -= 1 is equivalent to count = count - 1 . count is being evaluated before it's defined locally. When this happens you'll want to explicitly set the scope of count within the function as global (ie defined outside the function).

def main():
    global count

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM