Global and local variables in Python with examples


In Python, declaration of variables is not required. Means you don't need to specify whether it is an integer or string etc as Python is a dynamically typed language. In this post, let's learn about Global and local variables in Python along with examples.

1. Global Variables

Global variables are the variables which are declared outside the function or in global scope. A global variable can be accessed through out the program means they can be accessible in both inside and outside of the functions.

Example: 1

x = "I'm global"

def func():
 print("Inside function, x value:", x)

func()
print("Outside function, x value:", x)

Run here

If you run the above program, you can notice that x value is same in both inside and outside functions.

Results

Inside function, x value: I'm global
Outside function, x value: I'm global

Consider you want to modify the value of x inside function, let's see what will happen if you do so:

x = 10

def func():
 x = x * x 
 print("Square of x: ", x)
func()

Run here

Results

UnboundLocalError: local variable 'x' referenced before assignment

This is because Python treats x inside the function as local variable. In order to make this work, use the global keyword as shown below.

x = 10

def func():
 global x
 x = x * x 
 print("Square of x: ", x)
func()

Run here

When you run the above program, you can see that the x value gets changed and the results will look like below:

Results

Square of x:  100

2. Local Variables

Local variables are the variables which are declared inside the function's body or in local scope. A local variable can be accessed only inside the function which it got declared.

def squareOfx():
 x = 10
 x = x * x 
 print("Square of x: ", x)

squareOfx()
print("x value outside function: ", x)

Run here

When you run the above program, it generates the below error:

NameError: name 'x' is not defined

This is because x is alive only inside the function and hence it can be accessable only inside the function it is declared.

Suppose if global and local variables shares the same name:

x = 5
print("x value outside function before function call: ", x)

def func():
 x = 10
 print("x value inside function: ", x)

func()
print("x value outside function after function call: ", x)

Run here

When you run the above program, you can notice that the x value inside function will be 10 and outside the function will be 5. Python treats global and local variables seperately even though it shares same name.

Result

x value outside function before function call:  5
x value inside function:  10
x value outside function after function call:  5