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

Question:

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

Asked By: YohanRoth

||

Answers:

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 (i.e. defined outside the function).

def main():
    global count
Answered By: Matt S
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.