64

Possible Duplicate:
Using global variables in a function other than the one that created them

I have the following script:

COUNT = 0

def increment():
    COUNT = COUNT+1

increment()

print COUNT

I just want to increment global variable COUNT, but this gives me 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 is it so?

ROMANIA_engineer
  • 51,252
  • 26
  • 196
  • 186
user873286
  • 7,409
  • 7
  • 28
  • 38
  • 1
    The use of `global` among beginners is usually a sign of bad design. – Rik Poggi May 08 '12 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. – Ashwini Chaudhary May 08 '12 at 21:53
  • This should answer your question: http://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them Looks like Python won't change the global value unless you specify that it's what you want to do. – Phil Nicholson May 08 '12 at 21:46

2 Answers2

112

its a global variable so do this :

COUNT = 0

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

increment()

print COUNT

Global variables can be accessed without declaring the global but if you are going to change their values the global declaration is required.

cobie
  • 6,527
  • 9
  • 35
  • 58
30

This is because globals don't bleed into the scope of your function. You have to 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 and use that to do something. If you need to have data accessible from a range of functions, consider making a class.

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

Gareth Latty
  • 82,334
  • 16
  • 175
  • 177