Scope and Module
Variable Scope, LEGB Rule, Global Keyword और Module — Python की modular programming को मास्टर करें! अपने code को organized और reusable बनाना सीखें।
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।
Python me variable scope do prakar ke hote hain:
Program ke har jagah accessible
Main program me define kiye gaye variable
Sirf function ke andar accessible
Function ke andar define kiye gaye variable
📊 Scope Visualization
x = 10 # global variabley = 20 # local variableprint(x) # ✅ access globalprint(y) # ✅ access localprint(x) # ✅ access globalprint(y) # ❌ Error! local variable1. 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 variable ko program ke kisi bhi hisse me access kiya ja sakta hai।
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 programHello Rahul Goodbye Rahul Welcome Rahul
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)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।
NameError aata hai!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) # ❌ NameErrorInside function: 30
Ek program likho jisme 3 number input kare aur user define function ka use karke unka average calculate kare।
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()Enter number 1: 10 Enter number 2: 20 Enter number 3: 30 Average = 20.0
Jab global aur local variable ka naam same ho to function me local variable ko preference milti hai।
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 hogaInside 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:
Local
Function ke andar
Enclosing
Outer function me
Global
Main program me
Built-in
Python ka built-in
🔍 LEGB Search Flow
Sabse pehle function ke andar ka variable check hota hai
def printName():
name = "Deepak" # local variable
print("Hi", name) # L → local me mil gaya!
printName()Nested function me outer function ka variable check hota hai
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()Main program me define kiya gaya variable
name = "Rahul" # global variable
def printName():
print(name) # L ❌ → E ❌ → G ✅ global me mil gaya!
printName()Python ke pre-defined functions aur constants
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")) # 5Ek program me saare scopes ko samjhein — comment hata kar dekho kya output aata hai!
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)3.141592653589793
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 unchangedk before function = 25 k inside function = 10 k after function = 25
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।
global <variable name>global keyword ke, function ke andar global variable ko assign karne se naya local variable ban jata hai — original global variable change nahi hota!Bina global keyword ke function me variable assign karne par kya hota hai:
count = 0 # global variable
def increment():
count = count + 1 # ❌ UnboundLocalError!
print(count)
increment()UnboundLocalError: local variable 'count' referenced before assignment
Global keyword use karne par function me global variable ko modify kar sakte hain:
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)Inside: 1 Inside: 2 Inside: 3 Outside: 3
def add():
global a # a ko global banaya
a = 5
add()
print(a) # ✅ 5 — function ke bahar bhi accessible5
def setup():
global name, age, city
name = "Piyush"
age = 20
city = "Delhi"
setup()
print(f"{name}, {age} years old, from {city}")Piyush, 20 years old, from Delhi
📊 Global vs Local — Quick Reference
| Feature | Global Variable | Local Variable |
|---|---|---|
| Defined | Main program me | Function ke andar |
| Access | Kahi bhi | Sirf function me |
| Lifetime | Program end tak | Function end tak |
| Modify in func | global keyword chahiye | Directly 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 create karne ke 3 Steps:
Naya .py file me functions likho
import keyword se module load karo
Module ke functions ko call karo
Creating & Using Module →
Step 1: Creating Module— Naya python file me functions likhoModule 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
def add(a, b):
d = a + b
return d
def m(a, b):
d = a * b
return dStep 2: Importing Module— import function ka use karke module ko load karoimport keyword ka use karke module ko import kiya jata hai।
import <module name>import writeStep 3: Calling Module Objects— Import kiye gaye module ke functions ko use karoImport kiye gaye module ko call karne ke liye module_name.function_name() syntax use hota hai।
import write
print(write.add(4, 6)) # Output: 10
print(write.m(4, 6)) # Output: 2410 24
Area of triangle aur Area of circle ke liye ek module create karo aur use call karo।
# 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 dimport 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.24Area of Triangle: 12.0 Area of Circle: 50.24
Import Techniques →
Python me module import karne ke multiple tarike hain:
1. import module— Poora module import karoimport math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.02. from module import *— Module ke saare functions import karoIs tarike me module name likhne ki zaroorat nahi hoti — directly function name use hota hai।
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 function— Specific function import karoJab sirf kuch specific functions chahiye tab ye use karo — memory efficient hai।
from math import pi, sqrt
print(pi) # ✅ works
print(sqrt(25)) # ✅ works
# print(cos(0)) # ❌ not imported!4. import module as alias— Module ko nickname (alias) doimport math as m
print(m.pi) # 3.141592653589793
print(m.sqrt(49)) # 7.0| Import Style | Usage | Best For |
|---|---|---|
| import math | math.pi, math.sqrt() | Clear, organized code |
| from math import * | pi, sqrt() | Quick scripts |
| from math import pi | pi | Memory efficient |
| import math as m | m.pi, m.sqrt() | Short alias |
Questions & Programs →
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 — 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 ffrom 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.")===== 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
Ek calculator module banao jisme add, subtract, multiply, divide functions hon।
# 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 / bimport 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)}")Enter first number: 20 Enter second number: 5 Addition: 25 Subtraction: 15 Multiplication: 100 Division: 4.0
Ek module banao jo percentage calculate kare aur grade return kare।
# 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)"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}")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 💪
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