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?
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.
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.
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.
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.
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