Scope and module

M3-R5.1 · Chapter 8: Scope and Modules · 8 min read

In Python, scope and names (identifiers) are essential concepts related to how variables and objects are accessed and managed within a program. The scope of a variable refers to the region of a program where that variable is defined and accessible. Here's a breakdown of the different types of variable scope:

  • A variable’s lifetime is the period of time for which it resides in the memory. The lifetime of variables inside a function is as long as the function executes. They are destroyed once you return from the function. Hence, a function does not remember the value of a variable from its previous calls.
  • 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 variable declared in one part of the program may not be accessible to the other parts. 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. Local Scope 2. Global scope             

Local Variables or Scope: A local scope refers to the area inside a function (or method) where variables are defined and accessible only within that function. It cannot be accessed outside the function. They are destroyed once we return from the function .

Characteristics of Local Scope:

  • A variable defined inside a function is local to that function.
  • It cannot be accessed outside the function.
  • It exists only during the execution of the function.

Example:1

def jai():

      msg = 'Hello How are you '

      print('Local Scope', msg)

jai()

#print(msg)  # Error: name is not defined

Example 2:

def fund ( ) :

    x=9      # Local scope

    print(x)

fund ( )

In the Example 1:

  • msg is a local variable.
  • It’s only accessible inside the jai() function.
  • Trying to print msg outside the function will raise a NameError.

Example 3

def jai():

    x = 10

    y=30

    print("jai:", x)

def jai1():

    x = 20

    print("jai1:", x)

    print(y)

jai()                            # Outputs: jai: 10

jai1()                          # Outputs: jai1: 20

Example : Local Variables in Loops (Inside Function)

def print_numbers():

    for i in range(3):

        num = i * 2

        print("Inside loop:", num)

print_numbers()

# print(num)        # Error: 'num' is local to the function

Example : Function Arguments Are Local Variables

def add(a, b):  # 'a' and 'b' are local to the function

    result = a + b

    print("Sum is:", result)

add(3, 4)          

# print(result)     # Error: 'result' not accessible outside

Example : Multiple Local Variables in One Function

def cal_area(length, width):

    area = length * width

    unit = "square meters"

    print("Area:",area ,unit)

cal_area(5, 3)

# print(area)  #  Error: 'area' is local

Example : Local Variable Initialized Conditionally

def status(score):

    if score >= 60:

        result = "Pass"

    else:

        result = "Fail"

    print("Status:", result)

status(75)

status(45)

Global Variables or Scope:  The global scope refers to the area of a program where a variable is accessible from anywhere in the code after it has been declared.

OR

A global scope is the outermost scope in a program where variables are declared outside of all functions, classes, or blocks. These variables are accessible from any part of the code, including inside functions (unless shadowed by a local variable of the same name).

Characteristics:

  • Declared outside all functions or blocks.
  • Accessible throughout the program.
  • Can be read inside functions, but to modify them, you often need a special keyword (like global in Python).

         Example:  

msg= 'Hello How are your'

def greet():

    print('Local Access', msg)

greet()

print('Global Access', msg)

y=10 # Global scope

def jai( ):

     print(y)

jai( )

  • The global names are variables assigned at the top level of the enclosing module file. It means that it is visible everywhere within the program.
  • The global names must be declared only if they are assigned within a function.
  • Global variables must be referenced within a function without being declared

Example :#Modifying Global Variables Inside a Function

x = 10

def jai():

       x = x + 5  # UnboundLocalError: local  variable 'x'

    print(x)

jai()

:#Modifying Global Variables Inside a Function using global Keyword

x = 10

def jai():

    global x

    x = x + 5

jai()

print(x)       # Output: 15

count = 0

def jai():

    global count

    count += 1

jai()

jai()

print(count)  # Output: 2

score = 0

def add():

    global score

    score += 10

def mark():

    print("Score:",score)

add()

add()

mark()  # Output: Score: 20

Example: Demo of local and global variables.

total = 0; #Global Variable

def sum( arg1, arg2 ): # Function definition

      total = arg1 + arg2; # Here total Is local variable

       print(“Inside the function local total : “, total)

       return total

sum( 20, 40 )                    

print(“Outside the function global total : “, total)

When the above code is executed, it produces the following result:

 OUTPUT:        Inside the function local total: 60

Outside the function global total: 0

The LEGB rule in Python describes the order in which the interpreter looks up variable names. It stands for:

  • L - Local           Names assigned within a function (or lambda), including its parameters.
  • E - Enclosing    Names in the local scope of any enclosing functions (for nested functions).
  • G - Global        Names assigned at the top-level of a module or declared global in a function.
  • B - Built-in       Names preassigned in the built-in names module (like len, range, etc.)

Example:

y=10     # Global Scope

def jai():

    #y=15 #Enclosing Scope

    def jai1():

        #y=5    # Local Scope

        print("Y",y)

    jai1()

jai()

pi=10

def jai():

    pi=20 #Enclosing Scope

    def jai1():

        nonlocal pi

        pi=30    # Local Scope

        print(pi)

    jai1()                                 

    print(pi)

jai()

print(pi)

from math import pi

#pi=10

def jai():

    #pi=20 #Enclosing Scope

    def jai1():

        #pi=30    # Local Scope

        print(pi)

    jai1()

jai()