The keyword "global" has a special purpose . If you look into the help docstring of this keyword, you must notice this line :
Now . In python , if you declare a variable outside the scope of all functions or classes, it is AVAILABLE GLOBALLY. Meaning I can use it anywhere anytime.
But what is NOT clear , is , you CANNOT change the value\contents of this variable.
Bringing statefulness into your program (e.x an integrating counter ), might need you to keep updating some variable's value . That means, functions must be able to change that value.
Hence, the keyword "global" .
If you want a function to be able to change the value of a variable declared outside the scope of that function, then you need to declare that variable as a global variable INSIDE that function.
Now one can see , that the value changed .
# Add for a list example
It would be impossible to assign to a global variable without "global "
The word to note is "Assign"
But what is NOT clear , is , you CANNOT change the value\contents of this variable.
Bringing statefulness into your program (e.x an integrating counter ), might need you to keep updating some variable's value . That means, functions must be able to change that value.
Hence, the keyword "global" .
Let's try a piece of code . Steps:
- Create a variable.
- Create a function that does not accept an argument.
- Print the variable in function.
- Call that function.
>>> name 'Arindam' >>> def funcAnother(): print name >>> funcAnother() Arindam
Now we try to change the value of this variable inside this function.
- Create a variable.
- Create a function that does not accept an argument.
- print the variable in function.
- Change the value of that variable.
- Again try to change it .
>>> name = 'Arindam' >>> def funcUpper(): print 'Before change:', name name = name.upper() print 'New value:', name >>> funcUpper() Before change: Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> funcUpper() File "<pyshell#5>", line 2, in funcUpper print 'Before change:', name UnboundLocalError: local variable 'name' referenced before assignment
If you want a function to be able to change the value of a variable declared outside the scope of that function, then you need to declare that variable as a global variable INSIDE that function.
>>> def funcUpper(): global name print name name = name.upper() >>> funcUpper() Arindam >>> name 'ARINDAM'
Now one can see , that the value changed .
# Add for a list example
No comments:
Post a Comment