Global, Local & Free Variables in Python with Example

Table of Contents

Python defines three types of variables based on where they are created and used. They are Global, Local & Free variables.

This article explains Local, Global & Free Variable in Python programming with example.

Local Variable

If a variable is bound to a block then it is known as local variable of that block, unless declared as nonlocal or global.

In other words, any variables declared inside the function or in the local scope are known as local variables.

Scope of local variable is local to where they are defined which means they exist only within their scope.

Example 1: Local Variable


# Local Variable

def my_function():
    msg = "Hello, World!"
    print(msg)

my_function()

Output

Hello, World!

In this example local variable msg is created and used within my_function.

Example 2: Using Local Variable Outside of Scope


# Local Variable

def my_function():
    msg = "Hello, World!"

print(msg)

Output

NameError: name 'msg' is not defined

Here msg is local variable and its scope is within my_function code block. Variable msg is created within my_function and its scope is within my_function. So, we cannot use msg outside of my_function and that is why on printing msg we get NameError in the above program.

Global Variable

If any variable is bounded at the module level in the Python program then it is known as global variable.

In other words, a variables declared outside of the function or in the global scope are known as a global variables.

Scope of global variable is global to the Python program which means they can be used anywhere in the program (inside or outside of function).

Global Variable Example


# Global Variable

msg = "Hello, World!"

def my_function():
    print('Inside  of function:', msg)

print('Outside of function:', msg)
my_function()

Output

Outside of function: Hello, World!
Inside  of function: Hello, World!

Here, variable msg is defined in global scope i.e. at module level or root level so it can be used inside or outside of function.

Free Variable

In Python, there exist another type of variable known as Free Variable. If a variable is used in a code block but not defined there then it is known as free variable.

To understand the concept of free variable, lets consider following python program:

Free Variable Example


def outer():
    a = 20
  
    def inner():
        print('Value of a: %d' %(a))
    
    inner()

outer()

Output

Value of a: 20

Here variable a is defined in the scope of outer() function. If we look at inner() function, a is not defined there. But, function inner() is using variable a and hence variable a in inner() function is Free Variable.

Remember that variable a within outer() function is local.