Python variable Scoping

In python variable are of two types of variable, global variable and local variable.

Global variables are variables defined outside the function or in global scope such as in a file but outside the function.

Local variable are defined inside a function and they can only be used inside the function. Program can not access them outside. 

Global variable

Lets see an example of global variable

g = "global variable"
def print_g():
    print(g)

print_g()

Output:

global variable

Here g is global variable and we can access them inside the function. However, if we have to make changes to it we need to specify that we are making changes to global variable otherwise the program will throw an error. 

Example:

g = "global variable"
def print_g():
    g = "Hi! " +g
    print(g)

print_g()

This will throw an error like this:

Traceback (most recent call last):
  File "/home/10_global_local.py", line 12, in <module>
    print_g()
  File "/home/10_global_local.py", line 9, in print_g
    g = "Hi! " +g
UnboundLocalError: local variable 'g' referenced before assignment

This is because as we do concatenation operation using + operator inside the function, g is treated as local variable, which is not defined inside function. 

To resolve this issue we need to tell our program that we are accessing and using global variable. This is done using  global  keyword in python.

Example:

g = "global variable"
def print_g():
    global g
    g = "Hi! " +g
    print(g)

print_g()

Output:

Hi! global variable

Local variable

Lets see an example of local variable

def define_x():
    x = "local variable"
    print(x)
    
define_x()

Output:

local variable

Here x is a local variable because it is defined inside the function. If we try to access x outside the function it will throw an error. 

Nonlocal variable

If there are function inside a function and we want to access the variable we need to refer to them as nonlocal variable. For example.

Let’s say we have nested function as given below:

g = "Global variable"
def define_x():
    x = "local variable inside x"

    def define_y():

        nonlocal x # we need to access x using nonlocal keyword
        x = x * 2

        global g
        g = "Hi! " + g

        y = "local varaible inside y"
        print(x)
        print(g)
        print(y)

    define_y()

define_x()

Output:

local variable inside xlocal variable inside x
Hi! Global variable
local varaible inside y

Understanding variable scoping is very important because this make us understand how we can manipulate them and use them correctly in our program.

Leave a Reply

Your email address will not be published. Required fields are marked *