10

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

YohanRoth
  • 3,153
  • 4
  • 31
  • 58
  • 6
    You forgot to tell `main()` that `count` is global. – Frédéric Hamidi Apr 19 '16 at 13:59
  • 2
    (add `global count` to the first line of the main function) – damio Apr 19 '16 at 14:02
  • Best way would be to skip using global variables and to work with a function parameter and a return value instead. See: [Why are global variables evil?](http://stackoverflow.com/questions/19158339/why-are-global-variables-evil) – Matthias Apr 19 '16 at 14:19
  • 1
    Does this answer your question? [UnboundLocalError on local variable when reassigned after first use](https://stackoverflow.com/questions/370357/unboundlocalerror-on-local-variable-when-reassigned-after-first-use) – Tomerikoo Apr 26 '21 at 15:38
  • @Tomerikoo yes, it's a clear duplicate. (I've continued working on the question in a way that makes this more obvious.) – Karl Knechtel Feb 07 '23 at 01:23

1 Answers1

16

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
Matt S
  • 14,976
  • 6
  • 57
  • 76