76

From this code:

COUNT = 0

def increment():
    COUNT = COUNT + 1

increment()

I get the following error:

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    increment()
  File "test.py", line 4, in increment
    COUNT = COUNT+1
UnboundLocalError: local variable 'COUNT' referenced before assignment

Why? How can I increment the global variable COUNT from inside the function?

3
  • This should answer your question: stackoverflow.com/questions/423379/… Looks like Python won't change the global value unless you specify that it's what you want to do. Commented May 8, 2012 at 21:46
  • 1
    The use of global among beginners is usually a sign of bad design. Commented May 8, 2012 at 21:51
  • without using global you can't modify the value of a global variable inside a function, you can only use it's value inside the function. But if you want to assign a new value to it then you've to use the global keyword first. Commented May 8, 2012 at 21:53

2 Answers 2

129

Use a global statement, like so:

COUNT = 0

def increment():
    global COUNT
    COUNT = COUNT+1

increment()

Global variables can be accessed without using global, but the statement is required in order to change the value of the global variable.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the solution. This one is better as I have tried already using "count += 1" alone but wasn't working. This worked for me. Thanks.
This no longer works. Old solution.
35

This is because globals don't bleed into the scope of the function. Use the global statement to force this for assignment:

>>> COUNT = 0
>>> def increment():
...     global COUNT
...     COUNT += 1
... 
>>> increment()
>>> print(COUNT)
1

Note that using globals is a really bad idea - it makes code hard to read, and hard to use. Instead, return a value from your function (using return) and use that to do something. If the same data needs to be accessible from a range of functions, consider making a class.

It's also worth noting that CAPITALS is generally reserved for constants, so it's a bad idea to name global variables like this. For normal variables, lowercase_with_underscores is preferred.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.