Updated date:

Global and Local Variables Python

I'm a software developer with a great interest in data analysis and statistics.

global-and-local-variables-python

Global variables are those variables that are declared outside a function scope but can be used in a function. To declare and use a global variable, we can use the keyword “global” before the variable name.
Let us try to understand the concept better with the help of some examples.

Variable Defined Inside Function And Used Outside It

Consider the following code.

#!/usr/bin/python3
 
def myFunct():
    a = 20
    print(a)
    
myFunct()
print(a)

The code will result in a NameError as the variable a is visible only to the function named myFunct. The print(a) towards the end of the program fails as the program assumes that the variable has not been defined yet. This is because the variable "a" is local to the function named myFunct().

Output of the above program will be:
Traceback (most recent call last):
20
File "G:\workspaces\py_ws\MyProj\org\pythontutorials\globalvslocal\globalAndLocal.py", line 13, in 
print(a)
NameError: name 'a' is not defined

We can add global a to myFunct() before setting and printing the value in order to make the code work. Consider the enhanced code below:

#!/usr/bin/python3
 
def myFunct():
    global a
    a = 20
    print("Inside myfunct(): a = ", a)
    
myFunct()
print("Value of a after first call to myFunct: a = ", a)
a = 10
print("After setting new value outside myFunct: a = ", a)
myFunct()
print("After calling myFunct for second time: a = ", a)

Output of the above code will be as follows:

Inside myfunct(): a = 20
Value of a after first call to myFunct: a = 20
After setting new value outside myFunct: a = 10
Inside myfunct(): a = 20
After calling myFunct for second time: a = 20

Variable Defined Outside Function And Used Inside It

Let us consider another example:

#!/usr/bin/python3
def callMe():
    print(msg)
    msg = "Called"
    
msg = "Calling..."
callMe()
print(msg)

What will happen if we execute the code? Will it run successfully?
The output of the above code will look like this:

Traceback (most recent call last):
File "G:\workspaces\py_ws\MyProj\org\pythontutorials\globalvslocal\scopedOutside.py", line 12, in 
callMe()
File "G:\workspaces\py_ws\MyProj\org\pythontutorials\globalvslocal\scopedOutside.py", line 8, in callMe
print(s)
UnboundLocalError: local variable 'msg' referenced before assignment

If we closely inspect the code, we can see that the variable msg is assigned the value “Calling” outside the callMe function. Then callMe() is called. Even though msg is declared outside the function before it is called, Python “assumes” that we want a local variable due to the assignment to msg inside of callMe(), so the print statement throws this error message.

Usually, a variable which is used inside of a function is regarded as a local variable, if it hasn’t been declared as a global variable.

To rectify the error, we need to modify the code as follows:

#!/usr/bin/python3
def callMe():
    global msg
    print(msg)
    msg = "Called"
    
msg = "Calling..."
callMe()
print(msg)

Now, it should print "Calling" and "Called" in two separate lines as intended. Output for the above program will be as follows:

Calling...
Called

Variables Inside Nested Functions

It is possible to define a function inside another function. Such functions are called nested functions.

Consider the following code:

#!/usr/bin/python3
def outer():
    x = 10
    def inner():
        global x
        x = 2
    print("Before calling inner(): x = ", x)
    print("Calling inner() now... ")
    inner()
    print("After calling inner(): x = ", x)
    
outer()
print("x in main: " + str(x))

The output of the above code will be:

Before calling inner(): x = 10
Calling inner() now...
After calling inner(): x = 10
x in main: 2

In the above program, the value of x is retained as 10 in the function outer() regardless of what inner() does with the variable. After calling inner(), a global variable exists with value 2. Since outer() in turn calls inner(), the print statement in main prints the value assigned to a global variable by inner().

© 2019 Sam Shepards