Scope and Module

Chapter 9 • Python
Chapter 9 • Python

Scope and Module

Variable Scope, LEGB Rule, Global Keyword और Module — Python की modular programming को मास्टर करें! अपने code को organized और reusable बनाना सीखें।

Variable Scope
LEGB Rule
Global Keyword
Modules

Introduction — Variable Scope →

Variable ke scope se nirdharit hota hai ki ye variable kahan se use kiye ja sakte hain aur variable ki pahchan tatha program ke kis hisse me ki ja rahi hai aur use kis prakar access kiya ja sakta hai।

📝 Scope ka matlab hai ki ek variable program ke kaunse hisse me visible aur accessible hai। Sahi scope samajhna bugs se bachne ke liye bahut zaroori hai!

Python me variable scope do prakar ke hote hain:

1. Global Scope

Program ke har jagah accessible

Main program me define kiye gaye variable

2. Local Scope

Sirf function ke andar accessible

Function ke andar define kiye gaye variable

📊 Scope Visualization

Global Scopex = 10   # global variable
Local Scope (function)y = 20   # local variableprint(x)  # ✅ access globalprint(y)  # ✅ access local
print(x)  # ✅ access globalprint(y)  # ❌ Error! local variable

1. Global Scope →

Main program me define kiye gaye variable global variable hote hain jinaka use program ke kisi bhi hisse me kiya ja sakta hai — chahe wo function ho ya loop.

📝 Global variables poori script me accessible rehte hain। Inhe function ke bahar define kiya jata hai।
Example — Global Variable

Global variable ko program ke kisi bhi hisse me access kiya ja sakta hai।

python
name = "Rahul"    # global variable

def greet():
    print("Hello", name)   # global variable accessed inside function

def farewell():
    print("Goodbye", name)  # same global variable in another function

greet()
farewell()
print("Welcome", name)     # global variable in main program
Output
Hello Rahul
Goodbye Rahul
Welcome Rahul
Example — Global Variable with Loop
python
total = 0    # global variable

for i in range(1, 6):
    total = total + i

def show():
    print("Sum =", total)  # accessing global variable

show()
print("Total =", total)
Output
Sum = 15
Total = 15

2. Local Scope →

User define function me banaya gaya variable local variable hota hai। Iska use keval usi function me kiya ja sakta hai — function ke bahar access karne par error aata hai।

⚠️ Local variable ko function ke bahar access karne par NameError aata hai!
Example — Local Variable
python
def calculate():
    a = 10        # local variable
    b = 20        # local variable
    result = a + b
    print("Inside function:", result)

calculate()
# print(a)   # ❌ NameError: name 'a' is not defined
# print(result)  # ❌ NameError
Output
Inside function: 30
Question — Average Calculator

Ek program likho jisme 3 number input kare aur user define function ka use karke unka average calculate kare।

python
def average():
    a = int(input("Enter number 1: "))   # local variable
    b = int(input("Enter number 2: "))   # local variable
    c = int(input("Enter number 3: "))   # local variable
    avg = (a + b + c) / 3
    print("Average =", avg)

average()
Output
Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
Average = 20.0
Example — Same Variable Name (Local vs Global)

Jab global aur local variable ka naam same ho to function me local variable ko preference milti hai।

python
x = "Global X"     # global variable

def test():
    x = "Local X"   # local variable (same name)
    print("Inside function:", x)   # local variable print hoga

test()
print("Outside function:", x)   # global variable print hoga
Output
Inside function: Local X
Outside function: Global X

⭐ LEGB Rule →

Jab kisi program ya function ke andar Python koi variable access karta hai to ek specific order follow karta hai jise LEGB Rule kehte hain। Python hamesha is order me variable search karta hai:

L

Local

Function ke andar

E

Enclosing

Outer function me

G

Global

Main program me

B

Built-in

Python ka built-in

💡 Python sabse pehle Local scope check karta hai, phir Enclosing, phir Global, aur ant me Built-in। Jis level par variable mil jaye, wahi use hota hai!

🔍 LEGB Search Flow

1️⃣ Local — sabse pehle local variable check
2️⃣ Enclosing — phir enclosing block check
3️⃣ Global — main program me check
4️⃣ Built-in — pre-defined function check
L
Local Scope

Sabse pehle function ke andar ka variable check hota hai

python
def printName():
    name = "Deepak"    # local variable
    print("Hi", name)  # L → local me mil gaya!

printName()
E
Enclosing Scope

Nested function me outer function ka variable check hota hai

python
def outer():
    name = "Enclosing"   # enclosing variable
    
    def inner():
        # name nahi hai local me → enclosing check karo
        print("Hi", name)   # E → enclosing me mil gaya!
    
    inner()

outer()
G
Global Scope

Main program me define kiya gaya variable

python
name = "Rahul"    # global variable

def printName():
    print(name)   # L ❌ → E ❌ → G ✅ global me mil gaya!

printName()
B
Built-in Scope

Python ke pre-defined functions aur constants

python
from math import pi

# pi kahi define nahi kiya humne — ye built-in hai
print(pi)   # 3.141592653589793

# print, len, range — ye sab built-in hain
print(len("Hello"))   # 5
Complete LEGB Example

Ek program me saare scopes ko samjhein — comment hata kar dekho kya output aata hai!

python
from math import *

# pi = "global"            # uncomment karke G test karo

def enc():
    # pi = "enclosing"      # uncomment karke E test karo
    
    def local():
        # pi = "local"      # uncomment karke L test karo
        print(pi)           # ye LEGB rule follow karega
    
    local()

enc()

# Default: pi = 3.141592653589793 (Built-in)
Output
3.141592653589793
💡 Upar ke code me ek-ek comment hata kar run karo — tumhe LEGB rule practically samajh aa jayega!
Example — Variable Scope Behavior
python
def func1():
    k = 10
    print("k inside function =", k)   # local k = 10

k = 25                               # global k = 25
print("k before function =", k)
func1()
print("k after function =", k)       # global k unchanged
Output
k before function = 25
k inside function = 10
k after function = 25
📝 Function ke andar ka k = 10 (local) aur bahar ka k = 25 (global) — dono alag-alag variables hain!

⭐ Global Keyword →

global keyword ka use karke kisi bhi function ke andar ke variable ko global variable banaya ja sakta hai। Isse function ke andar se global variable ko modify kiya ja sakta hai।

Syntax
python
global <variable name>
⚠️ Bina global keyword ke, function ke andar global variable ko assign karne se naya local variable ban jata hai — original global variable change nahi hota!
Example — Without global keyword

Bina global keyword ke function me variable assign karne par kya hota hai:

python
count = 0    # global variable

def increment():
    count = count + 1    # ❌ UnboundLocalError!
    print(count)

increment()
Error
UnboundLocalError: local variable 'count' referenced before assignment
Example — With global keyword ✅

Global keyword use karne par function me global variable ko modify kar sakte hain:

python
count = 0    # global variable

def increment():
    global count         # declare as global
    count = count + 1    # ✅ now it works!
    print("Inside:", count)

increment()
increment()
increment()
print("Outside:", count)
Output
Inside: 1
Inside: 2
Inside: 3
Outside: 3
Example — Creating global variable inside function
python
def add():
    global a         # a ko global banaya
    a = 5

add()
print(a)   # ✅ 5 — function ke bahar bhi accessible
Output
5
Example — Multiple global variables
python
def setup():
    global name, age, city
    name = "Piyush"
    age = 20
    city = "Delhi"

setup()
print(f"{name}, {age} years old, from {city}")
Output
Piyush, 20 years old, from Delhi

📊 Global vs Local — Quick Reference

FeatureGlobal VariableLocal Variable
DefinedMain program meFunction ke andar
AccessKahi bhiSirf function me
LifetimeProgram end takFunction end tak
Modify in funcglobal keyword chahiyeDirectly modify ho sakta hai

📦 Module — Introduction →

Python me jo bhi program banaya jata hai wo module ke roop me jana jata hai। Ek module functions, classes, aur variables ka sangrah hota hai।

🏗️ Module kya hai?

  • Ek module .py extension ki file hota hai
  • Isme functions, classes, aur variables hote hain
  • Pre-defined modules jaise math, random, os import kiye ja sakte hain
  • User defined modules bhi banaye ja sakte hain
  • Code ko reusable aur organized banane ka best tarika
📝 Module use karne se code reusable hota hai — ek baar likho, baar baar use karo! Ye modular programming ka concept hai।

Module create karne ke 3 Steps:

Step 1Creating Module

Naya .py file me functions likho

Step 2Importing Module

import keyword se module load karo

Step 3Calling Objects

Module ke functions ko call karo

Creating & Using Module →

Step 1: Creating ModuleNaya python file me functions likho

Module banane ke liye ek new python file me user define functions likhe jate hain। Isme global environment nahi hota — keval functions hote hain।

write.py — Module File
python
# write.py — Module file

def add(a, b):
    d = a + b
    return d

def m(a, b):
    d = a * b
    return d
Step 2: Importing Moduleimport function ka use karke module ko load karo

import keyword ka use karke module ko import kiya jata hai।

Syntax
python
import <module name>
Example
python
import write
Step 3: Calling Module ObjectsImport kiye gaye module ke functions ko use karo

Import kiye gaye module ko call karne ke liye module_name.function_name() syntax use hota hai।

python
import write

print(write.add(4, 6))    # Output: 10
print(write.m(4, 6))      # Output: 24
Output
10
24
Question — Area Module (Triangle & Circle)

Area of triangle aur Area of circle ke liye ek module create karo aur use call karo।

area.py — Module File
python
# area.py — Module file

def AOT(b, h):
    """Area of Triangle"""
    d = (b * h) / 2
    return d

def AOC(r):
    """Area of Circle"""
    d = 3.14 * r * r
    return d
main.py — Main Program
python
import area

print("Area of Triangle:", area.AOT(4, 6))   # (4×6)/2 = 12
print("Area of Circle:", area.AOC(4))         # 3.14×4×4 = 50.24
Output
Area of Triangle: 12.0
Area of Circle: 50.24

Import Techniques →

Python me module import karne ke multiple tarike hain:

1. import modulePoora module import karo
python
import math
print(math.pi)       # 3.141592653589793
print(math.sqrt(16)) # 4.0
2. from module import *Module ke saare functions import karo

Is tarike me module name likhne ki zaroorat nahi hoti — directly function name use hota hai।

python
from math import *
print(pi)           # 3.141592653589793  (no math. prefix)
print(sqrt(16))     # 4.0

for i in range(10):
    print(pi)
3. from module import functionSpecific function import karo

Jab sirf kuch specific functions chahiye tab ye use karo — memory efficient hai।

python
from math import pi, sqrt
print(pi)        # ✅ works
print(sqrt(25))  # ✅ works
# print(cos(0)) # ❌ not imported!
4. import module as aliasModule ko nickname (alias) do
python
import math as m
print(m.pi)        # 3.141592653589793
print(m.sqrt(49))  # 7.0
Import StyleUsageBest For
import mathmath.pi, math.sqrt()Clear, organized code
from math import *pi, sqrt()Quick scripts
from math import pipiMemory efficient
import math as mm.pi, m.sqrt()Short alias

Questions & Programs →

📘 Question — Conversion Module

conversion.py name se ek module banao jisme teen function ho:
1. Dollar se Rupee conversion
2. Gram se KG conversion
3. Celsius se Fahrenheit conversion

Ek program bhi likho jo is module ko import karta hai aur user ki pasand ke aadhar par call karta hai।

conversion.py — Module File
python
# conversion.py — Conversion Module

def money(amt, rate):
    """Dollar to Rupee conversion"""
    amt = amt * rate
    return amt

def weight(gm):
    """Gram to KG conversion"""
    kg = gm / 1000
    return kg

def temp(t):
    """Celsius to Fahrenheit conversion"""
    f = 1.8 * t + 32
    return f
main.py — Main Program
python
from conversion import *

while True:
    print("\n===== Conversion Menu =====")
    print("Press 1 for Money Conversion (Dollar → Rupee)")
    print("Press 2 for Weight Conversion (Gram → KG)")
    print("Press 3 for Temperature Conversion (°C → °F)")
    print("Press 4 to Exit")

    ch = int(input("\nEnter your choice: "))

    if ch == 1:
        x = int(input("Enter amount in dollars: "))
        y = int(input("Enter rate of exchange: "))
        z = money(x, y)
        print(f"Converted amount: ₹{z}")

    elif ch == 2:
        x = int(input("Enter weight in grams: "))
        z = weight(x)
        print(f"Weight in KG: {z} kg")

    elif ch == 3:
        x = int(input("Enter temperature in Celsius: "))
        z = temp(x)
        print(f"Temperature in Fahrenheit: {z}°F")

    elif ch == 4:
        print("Thank you! Goodbye 👋")
        break

    else:
        print("Invalid choice! Try again.")
Output
===== Conversion Menu =====
Press 1 for Money Conversion (Dollar → Rupee)
Press 2 for Weight Conversion (Gram → KG)
Press 3 for Temperature Conversion (°C → °F)
Press 4 to Exit

Enter your choice: 1
Enter amount in dollars: 100
Enter rate of exchange: 83
Converted amount: ₹8300
Question — Calculator Module

Ek calculator module banao jisme add, subtract, multiply, divide functions hon।

calculator.py
python
# calculator.py

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        return "Error: Division by zero!"
    return a / b
main.py
python
import calculator as calc

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

print(f"Addition: {calc.add(a, b)}")
print(f"Subtraction: {calc.subtract(a, b)}")
print(f"Multiplication: {calc.multiply(a, b)}")
print(f"Division: {calc.divide(a, b)}")
Output
Enter first number: 20
Enter second number: 5
Addition: 25
Subtraction: 15
Multiplication: 100
Division: 4.0
Question — Student Grade Module

Ek module banao jo percentage calculate kare aur grade return kare।

student.py
python
# student.py

def percentage(m1, m2, m3, m4, m5):
    total = m1 + m2 + m3 + m4 + m5
    per = total / 5
    return per

def grade(per):
    if per >= 90:
        return "A+"
    elif per >= 80:
        return "A"
    elif per >= 70:
        return "B"
    elif per >= 60:
        return "C"
    elif per >= 50:
        return "D"
    else:
        return "F (Fail)"
main.py
python
from student import *

print("Enter marks for 5 subjects:")
m1 = int(input("Subject 1: "))
m2 = int(input("Subject 2: "))
m3 = int(input("Subject 3: "))
m4 = int(input("Subject 4: "))
m5 = int(input("Subject 5: "))

per = percentage(m1, m2, m3, m4, m5)
g = grade(per)
print(f"\nPercentage: {per}%")
print(f"Grade: {g}")
Output
Enter marks for 5 subjects:
Subject 1: 85
Subject 2: 92
Subject 3: 78
Subject 4: 88
Subject 5: 95

Percentage: 87.6%
Grade: A

Practice Questions →

In programs ko khud likhne ka prayaas karein — Chapter 9 ko aur acche se samajhne ke liye 💪

Q1
Write a program to demonstrate the difference between local and global variables.
Q2
Write a program that shows how Python finds variables using the LEGB rule.
Q3
Write a function that uses the global keyword to modify a counter variable.
Q4
Write a program with nested functions to demonstrate enclosing scope.
Q5
Create a module with functions to calculate area of rectangle, square, and circle.
Q6
Write a program that imports your custom module and calculates areas of different shapes.
Q7
Create a module 'string_utils.py' with functions: reverse_string, count_vowels, is_palindrome.
Q8
Write a program using 'from module import *' to use all functions from your module.
Q9
Create a module with a function that uses global keyword inside it. Import and test it.
Q10
Write a program that demonstrates all 4 types of import statements.
Q11
Create a module 'math_ops.py' with functions: factorial, is_prime, fibonacci.
Q12
Write a program that shows UnboundLocalError and then fix it using global keyword.
Q13
Create a conversion module with functions for: km to miles, kg to pounds, liters to gallons.
Q14
Write a program using module alias (import as) to organize your code.
Q15
Create a complete banking module with functions: deposit, withdraw, check_balance, transfer.

Chapter 9 — Key Points :

  • Global scope — poore program me accessible variable
  • Local scope — sirf function ke andar accessible variable
  • LEGB Rule — Local → Enclosing → Global → Built-in (search order)
  • global keyword — function me global variable modify karne ke liye
  • Module — .py file jisme reusable functions hote hain
  • 3 Steps: Create → Import → Call
  • 4 Import types: import, from...import *, from...import func, import...as
Hi! 👋
KnoblyAI
Online

Hello! 👋

Your futuristic AI learning companion

KnoblyAI can make mistakes. Double-check important replies.