Explain about Variable Scope in Python

The Scope holds the current set of variables and their values. Generally, The scope has been classified into two types

  • Local scope Variable can be accessed within the function
  • Global scope It can be used anywhere in the program

Local scope

A variable declared within the functions is known as a Local variable or Local scope.

Rules for Local scope

  • A variable with a local scope can be accessed only within the function.
  • When a variable is created inside the function, the variable is said to be local to it.
  • A local variable only exists while the function is executing.
  • The lifetime of local scope is still end of the functions

Example program

# Local scope

def var():
    a=5 #Local scope
    print("Inside a function",a)
var()
print("Outside a function",a)

#Output

Inside a function 5
Traceback (most recent call last):
  File "<string>", line 6, in <module>
NameError: name 'a' is not defined

Global scope

A variable declared outside of any functions is known as a global variable or global scope.

Rules for Global scope

  • A variable, with global scope can be used anywhere in the program.
  • We use a global keyword to read and write a global variable inside a function.
  • Lifetime of a global scope is end of the program

Example Program

# Global scope

a=5 #global scope
def var():
    a=5 #Local scope
    print("Inside a function",a)
var()
print("Outside a function",a)

#Output

Inside a function 5
Inside a function 10

Modifying Global Variable

# Modifying Global Variable

a = 10
def var():
    a = a + 5
    print("Modifying Global Variable",a)
var()

#Output


UnboundLocalError: local variable 'a' referenced before assignment

Without using the global keyword we cannot modify the global variable inside the function but we can only access the global variable.

# Modifying Global Variable

a = 10
def var():
    global a
    a = a + 5
    print("Modifying Global Variable",a)
var()

#Output

Modifying Global Variable 15

Related Blogs

return statement in python example: https://iterathon.tech//return-statement-in-python-example/

LEARN MORE ❣