Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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

like image 915
YohanRoth Avatar asked Dec 24 '22 06:12

YohanRoth


1 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
like image 137
Matt S Avatar answered Dec 26 '22 20:12

Matt S