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 (i.e. defined outside the function).
def main():
global count
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With