Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not increment global variable from function in python [duplicate]

Tags:

python

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?

like image 759
user873286 Avatar asked May 08 '12 21:05

user873286


People also ask

How do you increment a global variable inside a function in Python?

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.

What are two reasons why you should not use global variables in Python?

The reason global variables are bad is that they enable functions to have hidden (non-obvious, surprising, hard to detect, hard to diagnose) side effects, leading to an increase in complexity, potentially leading to Spaghetti code.

Can global variables be changed in functions Python?

Use of “global†keyword to modify global variable inside a function. If your function has a local variable with same name as global variable and you want to modify the global variable inside function then use 'global' keyword before the variable name at start of function i.e.


1 Answers

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.

like image 73
cobie Avatar answered Oct 12 '22 11:10

cobie