Search

21 December, 2018

Python Global Variables

The keyword "global" has a special purpose . If you look into the help docstring of this keyword, you must notice this line :

 It would be impossible to assign to a global variable without "global " 

The word to note is "Assign"

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


Let's try a piece of code . Steps:

  1. Create a variable.
  2. Create a function that does not accept an argument.
  3. Print the variable in function.
  4. Call that function.
>>> name
'Arindam'
>>> def funcAnother():
        print name

>>> funcAnother()
Arindam

Now we try to change the value of this variable inside this function.

  1. Create a variable.
  2. Create a function that does not accept an argument.
  3. print the variable in function.
  4. Change the value of that variable.
  5. 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