Local/Global Variables

Scope of Variables

All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.

The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python

  1. Global variables

  2. Local variables

Global vs. Local variables

Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.

This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope.

Example 1:

total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
   # Add both the parameters and return them."
   total = arg1 + arg2; # Here total is local variable.
   print("Inside the function local total : ", total)
   return total;

# calling sum function
sum( 10, 20 );
print("Outside the function global total : ", total)

Inside the function local total : 30

Outside the function global total : 0

Example 2:

x = 10
def hey():
    s = x
    s = s + 5
    print("Local variable x = ",s)
print("Global x = ",x)
hey()
print("Global x = ",x)

Global x = 10

Local variable x = 15

Global x = 10

Example 3:

x = 10
def chage():
    global x
    x = x + 5
    print("In function Value = ",x)
print("Before function calling x = ",x)
chage()
print("After function calling  x = ",x)

Before function calling x = 10

In function Value = 15

After function calling x = 15

Example 4:

c = 1
def hello():
    global c
    if c == 10 :
        c = 1
        return None
    print("Hello World Times {}".format(c))
    c = c + 1
    hello()
    
hello()

Hello World Times 1

Hello World Times 2

Hello World Times 3

Hello World Times 4

Hello World Times 5

Hello World Times 6

Hello World Times 7

Hello World Times 8

Hello World Times 9

Using variables from a function inside another function

Example 5:

def hello():
    c = 10 
    
    def hello1():
        global x
        c = c + 20
        print(c)
        
    hello1()
    
hello()

Above program will give error

Nonlocal variables are used in nested functions whose local scope is not defined. This means that the variable can be neither in the local nor the global scope

Example 6:

c = 100
def hello():
    c = 10 
    def hello1():
        nonlocal c
        c = c + 20
        print(c)
    hello1()
    print(c)
hello()
print(c)

30

30

100

Last updated