Python Notes
HubHistory of Python - Complete Guide 2026Python Applications - Complete Guide 2026Python Features - Complete Guide 2026What is Python? - Complete Guide 2026Why Learn Python? - Complete Guide 2026Your First Python Program – Hello World & Beyond 2026How to Install Python on Windows, Mac & Linux – Complete Guide 2026Install VS Code for Python – Complete Setup Guide with Extensions 2026Python Environment Setup – Virtual Environments, pip & Project Structure 2026Python IDLE – Complete Guide for Beginners 2026Python CommentsPython Data TypesPython Input and OutputPython OperatorsPython SyntaxPython Strings BasicsPython Type CastingPython VariablesBreak, Continue and Pass in PythonElif Statement in PythonFor Loop in PythonIf-Else Statement in PythonIf Statement in PythonNested If in PythonPattern Programs in PythonWhile Loop in PythonDecorators in PythonFunction Arguments in PythonFunctions Basics in PythonGenerators in PythonLambda Functions in PythonRecursive Functions in PythonReturn Statement in PythonScope of Variables in PythonAbstraction in PythonClasses and Objects in PythonConstructors in PythonEncapsulation in PythonInheritance in PythonMagic Methods (Dunder Methods) in PythonMethod Overriding in PythonPolymorphism in PythonPython Comprehensions – List, Dict, Set & GeneratorPython Dictionaries – Key-Value StorePython Dictionary Methods – Complete ReferencePython List Methods – All Built-in MethodsPython Lists – Complete GuidePython Set Methods – Complete ReferencePython Sets – Unordered Unique CollectionsPython Tuples – Immutable SequencesPython Asynchronous Programming with asyncioPython Context ManagersAdvanced Python DecoratorsAdvanced Python GeneratorsPython Iterators - Advanced GuidePython Memory ManagementPython MultiprocessingPython MultithreadingCRUD Operations in Python DatabasesMySQL with Python (mysql-connector-python)ORM Introduction with SQLAlchemyPostgreSQL with Python (psycopg2)SQLite3 with PythonIntroduction to DjangoDjango Models and ORMDjango REST API with DRFDjango ViewsIntroduction to FlaskFlask RoutingFlask Templates with Jinja2Email Automation with PythonPDF Automation with PythonSelenium Web Automation with PythonTask Scheduler with PythonWeb Scraping with PythonData Analysis with PythonData Cleaning with PythonData Visualization ProjectData Visualization with MatplotlibNumPy IntroductionPandas IntroductionStatistical Visualization with SeabornClassification AlgorithmsClustering AlgorithmsIntroduction to Machine LearningMachine Learning Project: Churn PredictionModel Evaluation and SelectionRegression AlgorithmsSave pipeline (includes preprocessing + model)AI Assistant ProjectCalculator ProjectChatbot ProjectExpense Tracker ProjectFace Detection ProjectPassword Generator ProjectWeather App ProjectPython Coding Interview QuestionsPython OOP Interview Questions and AnswersPython Master CheatsheetPython Interview Questions and AnswersPython Best PracticesCommon Python Errors and SolutionsPython Debugging TechniquesPython Learning Resources
Python mein variable scope ki complete guide — LEGB rule, local, enclosing, global, builtin scope, global/nonlocal keywords, aur closures. Hindi explanations ke saath real-world examples.
Scope decide karta hai ki ek variable kahan se accessible hai aur kitni der tak exist karta hai. Python LEGB Rule follow karta hai!
1️⃣ Local Scope (Function ke Andar)
Example
# ─────────────────────────────────────
# Local variables — function ke andar hi milte hain
# ─────────────────────────────────────
def calculate_tax():
# ← Local variables start yahan se
income = 500000 # Local
tax_rate = 0.20 # Local
tax = income * tax_rate # Local
print(f"Tax: ₹{tax:,.0f}")
# ← Local variables yahan khatam
calculate_tax()
# Bahar access karne ki koshish karo
try:
print(income) # ❌ NameError!
except NameError as e:
print(f"Error: {e}")
Example
# OUTPUT:
Tax: ₹100,000
Error: name 'income' is not defined
Example
# ─────────────────────────────────────
# Har function call ka apna local scope
# ─────────────────────────────────────
def greet(name):
message = f"Hello, {name}!" # Local to each call
print(message)
print(f" (id of message: {id(message)})")
greet("Rahul") # Apna local scope
greet("Priya") # Alag local scope
# Dono calls ka 'message' alag alag object hai
Example
# OUTPUT:
Hello, Rahul!
(id of message: 2163847234816)
Hello, Priya!
(id of message: 2163847234992)
2️⃣ Global Scope (Module Level)
Example
# ─────────────────────────────────────
# Global variables — poore module mein accessible
# ─────────────────────────────────────
# Global variables
APP_NAME = "WoHoTech Python Course" # UPPER_CASE convention
VERSION = "2.0"
MAX_STUDENTS = 100
def show_app_info():
# Global variables ko read kar sakte hain
print(f"App : {APP_NAME}")
print(f"Ver : {VERSION}")
print(f"Limit : {MAX_STUDENTS} students")
def check_enrollment(current):
# Global variable read karna — OK hai
available = MAX_STUDENTS - current
return available
show_app_info()
print(f"\nAvailable seats: {check_enrollment(75)}")
| App | WoHoTech Python Course |
| Ver | 2.0 |
| Limit | 100 students |
| Available seats | 25 |
3️⃣ global Keyword — Global Variable Modify Karna
Example
# ─────────────────────────────────────
# Global variable function ke andar modify karna
# ─────────────────────────────────────
counter = 0 # Global variable
def increment():
global counter # Global variable modify karna hai → declare karo
counter += 1
print(f"Counter: {counter}")
def reset():
global counter
counter = 0
print("Counter reset!")
print(f"Start: counter = {counter}")
increment()
increment()
increment()
reset()
increment()
print(f"Final: counter = {counter}")
| Start | counter = 0 |
| Counter | 1 |
| Counter | 2 |
| Counter | 3 |
| Counter | 1 |
| Final | counter = 1 |
Example
# ─────────────────────────────────────
# WITHOUT global keyword — kya hoga?
# ─────────────────────────────────────
score = 100 # Global
def add_points_wrong(points):
# 'global score' nahi likha
try:
score += points # ❌ UnboundLocalError!
except UnboundLocalError as e:
print(f"Error: {e}")
def add_points_right(points):
global score # ✅ Declare karo
score += points
add_points_wrong(50) # Error!
add_points_right(50) # ✅
print(f"Score: {score}") # 150
Example
# OUTPUT:
Error: local variable 'score' referenced before assignment
Score: 150
4️⃣ Enclosing Scope — Nested Functions
Example
# ─────────────────────────────────────
# Enclosing scope — outer function ka variable
# inner function read kar sakta hai
# ─────────────────────────────────────
def outer():
message = "Main outer function ka variable hoon"
def inner():
# Enclosing scope se read kar raha hai
print(f"Inner ne padha: {message}")
inner()
print(f"Outer ne padha: {message}")
outer()
Code example
# OUTPUT:
Inner ne padha: Main outer function ka variable hoon
Outer ne padha: Main outer function ka variable hoonExample
# ─────────────────────────────────────
# Multiple nesting levels
# ─────────────────────────────────────
def level_1():
x = "Level 1"
def level_2():
y = "Level 2"
def level_3():
z = "Level 3"
# Saare enclosing variables accessible hain
print(f"Level 3 dekh sakta hai: {x}, {y}, {z}")
level_3()
print(f"Level 2 dekh sakta hai: {x}, {y}")
# print(z) # ❌ z accessible nahi hai yahan
level_2()
print(f"Level 1 dekh sakta hai: {x}")
level_1()
| Level 3 dekh sakta hai | Level 1, Level 2, Level 3 |
| Level 2 dekh sakta hai | Level 1, Level 2 |
| Level 1 dekh sakta hai | Level 1 |
5️⃣ nonlocal Keyword — Enclosing Variable Modify Karna
Example
# ─────────────────────────────────────
# nonlocal — enclosing scope variable modify karna
# ─────────────────────────────────────
def make_counter(start=0):
"""Counter closure with nonlocal"""
count = start
def increment(step=1):
nonlocal count # Enclosing variable modify karna
count += step
return count
def decrement(step=1):
nonlocal count
count -= step
return count
def reset():
nonlocal count
count = start
return count
def get_value():
return count # Read only — nonlocal zaroori nahi
return increment, decrement, reset, get_value
# Counter banao
inc, dec, rst, val = make_counter(10)
print(f"Start : {val()}")
print(f"+1 : {inc()}")
print(f"+1 : {inc()}")
print(f"+5 : {inc(5)}")
print(f"-2 : {dec(2)}")
print(f"Reset : {rst()}")
print(f"Final : {val()}")
| Start | 10 |
| +1 | 11 |
| +1 | 12 |
| +5 | 17 |
| -2 | 15 |
| Reset | 10 |
| Final | 10 |
6️⃣ Built-in Scope
Example
# ─────────────────────────────────────
# Built-in scope — Python ke pre-defined names
# ─────────────────────────────────────
import builtins
# Kuch built-in names
builtin_names = dir(builtins)
print(f"Total built-in names: {len(builtin_names)}")
# Kuch important ones
important_builtins = ['print', 'len', 'range', 'type', 'int', 'str',
'list', 'dict', 'tuple', 'set', 'bool',
'True', 'False', 'None', 'sum', 'max', 'min']
print("\nImportant built-ins:")
for b in important_builtins:
print(f" {b}", end=" ")
print()
Example
# OUTPUT:
Total built-in names: 152
Important built-ins:
print len range type int str list dict tuple set bool True False None sum max min
Example
# ─────────────────────────────────────
# Built-in ko shadow karna — BAD PRACTICE!
# ─────────────────────────────────────
# ❌ NEVER DO THIS
list = [1, 2, 3] # Built-in 'list' ko shadow kiya!
try:
new_list = list("hello") # ❌ TypeError!
except TypeError as e:
print(f"Error: {e}")
# ✅ Name reset karo
del list # Built-in restore ho jaata hai
new_list = list("hello") # ✅ Works again
print(new_list) # ['h', 'e', 'l', 'l', 'o']
7️⃣ LEGB Rule in Action
Example
# ─────────────────────────────────────
# LEGB Rule demonstration
# ─────────────────────────────────────
x = "Global x" # Global scope
def outer_func():
x = "Enclosing x" # Enclosing scope
def inner_func():
x = "Local x" # Local scope
print(f"Inner sees: {x}") # Local
def middle_func():
# Local x nahi hai → Enclosing x use hoga
print(f"Middle sees: {x}") # Enclosing
inner_func()
middle_func()
print(f"Outer sees: {x}") # Enclosing
def standalone():
# Local x nahi, Enclosing bhi nahi → Global use hoga
print(f"Standalone sees: {x}") # Global
outer_func()
standalone()
print(f"Module sees: {x}") # Global
| Inner sees | Local x |
| Middle sees | Enclosing x |
| Outer sees | Enclosing x |
| Standalone sees | Global x |
| Module sees | Global x |
8️⃣ Closures — Enclosing Scope ka Magic
Example
# ─────────────────────────────────────
# Closure — function jo outer variable "pakad" leta hai
# ─────────────────────────────────────
def make_greeting(greeting_word):
"""Greeting word close kar ke ek function return karta hai"""
def greet(name):
# greeting_word — closure variable
return f"{greeting_word}, {name}! 🙏"
return greet
# Alag alag closures banao
namaste = make_greeting("Namaste")
hello = make_greeting("Hello")
good_morning = make_greeting("Good Morning")
print(namaste("Rahul")) # Namaste, Rahul! 🙏
print(hello("Alex")) # Hello, Alex! 🙏
print(good_morning("Priya")) # Good Morning, Priya! 🙏
# Closure variable check karo
print(f"\nnamaste.__closure__: {namaste.__closure__}")
print(f"Closed variable: {namaste.__closure__[0].cell_contents}")
Example
# OUTPUT:
Namaste, Rahul! 🙏
Hello, Alex! 🙏
Good Morning, Priya! 🙏
namaste.__closure__: (<cell at 0x...>,)
Closed variable: Namaste
Example
# ─────────────────────────────────────
# Real-world closure: Discount Calculator
# ─────────────────────────────────────
def make_discount_calculator(discount_percent):
"""Specific discount ke liye calculator closure"""
def calculate(original_price):
discount_amount = original_price * discount_percent / 100
final_price = original_price - discount_amount
return {
"original": original_price,
"discount": f"{discount_percent}%",
"saved": discount_amount,
"final": final_price
}
return calculate
# Alag alag discount calculators
sale_10 = make_discount_calculator(10)
sale_25 = make_discount_calculator(25)
sale_50 = make_discount_calculator(50)
def print_pricing(label, calc, price):
result = calc(price)
print(f" {label}: ₹{result['original']} → ₹{result['final']} (save ₹{result['saved']:.0f})")
item_price = 2000
print(f"🛒 Item Price: ₹{item_price}")
print_pricing("Sale 10%", sale_10, item_price)
print_pricing("Sale 25%", sale_25, item_price)
print_pricing("Sale 50%", sale_50, item_price)
| 🛒 Item Price | ₹2000 |
| Sale 10%: ₹2000 | ₹1800.0 (save ₹200) |
| Sale 25%: ₹2000 | ₹1500.0 (save ₹500) |
| Sale 50%: ₹2000 | ₹1000.0 (save ₹1000) |
9️⃣ Variable Shadowing
Example
# ─────────────────────────────────────
# Variable shadowing — same naam, alag scope
# ─────────────────────────────────────
name = "Python" # Global
def show_name():
name = "Java" # Local — shadows global 'name'
print(f"Inside function: {name}") # Java
print(f"Before call: {name}") # Python
show_name()
print(f"After call: {name}") # Python (unchanged!)
| Before call | Python |
| Inside function | Java |
| After call | Python |
🏗️ Practical Example: Configuration Manager
Example
# ─────────────────────────────────────
# Scope-aware configuration system
# ─────────────────────────────────────
# Global defaults
DEFAULT_CONFIG = {
"db_host": "localhost",
"db_port": 5432,
"debug": False,
"max_connections": 10,
}
_current_config = DEFAULT_CONFIG.copy() # Module-level
def configure(**overrides):
"""Configuration update karo"""
global _current_config
_current_config.update(overrides)
print(f"✅ Config updated: {list(overrides.keys())}")
def get_config(key=None):
"""Config read karo"""
if key:
return _current_config.get(key)
return _current_config.copy()
def reset_config():
"""Default config restore karo"""
global _current_config
_current_config = DEFAULT_CONFIG.copy()
print("🔄 Config reset to defaults")
# Usage
print("📋 Default Config:")
for k, v in get_config().items():
print(f" {k}: {v}")
configure(db_host="prod.server.com", debug=True, max_connections=50)
print("\n📋 Updated Config:")
print(f" db_host: {get_config('db_host')}")
print(f" debug: {get_config('debug')}")
print(f" max_connections: {get_config('max_connections')}")
reset_config()
print(f"\n db_host after reset: {get_config('db_host')}")
| db_host | localhost |
| db_port | 5432 |
| debug | False |
| max_connections | 10 |
| ✅ Config updated | ['db_host', 'debug', 'max_connections'] |
| db_host | prod.server.com |
| debug | True |
| max_connections | 50 |
| db_host after reset | localhost |
❓ Interview Questions
Q1: LEGB rule kya hai?
Local → Enclosing → Global → Built-in Python isi order mein variable dhundhta hai.
Q2: global aur nonlocal mein kya fark hai?
python example
x = "global"
def outer():
x = "enclosing"
def inner():
global x # Module-level x access karo
nonlocal x # Enclosing scope x access karo (yahan se ek hi use karo)global→ module-level variable modify karnanonlocal→ nearest enclosing scope ka variable modify karna
Q3: Closure kya hai?
Closure ek function hai jo apne enclosing scope ke variables ko remember karta hai even after outer function execute ho chuka ho.
Q4: UnboundLocalError kab aata hai?
python example
x = 10
def func():
print(x) # ❌ UnboundLocalError!
x = 20 # Python mein x ko local maan leta hai
# Fix:
def func():
global x
print(x)
x = 20📋 Summary
┌─────────────────────────────────────────────────────┐
│ SCOPE — KEY CONCEPTS │
├─────────────────────────────────────────────────────┤
│ ✅ LEGB: Local → Enclosing → Global → Built-in │
│ ✅ Local scope function ke andar hota hai │
│ ✅ Global variables poore module mein accessible │
│ ✅ global keyword se global var modify karo │
│ ✅ nonlocal se enclosing var modify karo │
│ ✅ Built-in names ko shadow mat karo │
│ ✅ Closures enclosing variables "close" karte hain │
│ ✅ Har function call ka apna local scope hota hai │
└─────────────────────────────────────────────────────┘
🚀 Next: Python Decorators — advanced feature seekhne ke liye decorators.mdx padhein!⚠️ Common Mistakes
Mistake 1: Global variable ko bina global keyword modify karna
python example
count = 0
def increment():
count += 1 # ❌ UnboundLocalError!
return count
try:
increment()
except UnboundLocalError as e:
print(f"Error: {e}")Example
# OUTPUT:
Error: local variable 'count' referenced before assignment
🔴 Problem: Jab aap kisi variable ko assign karte ho function mein, Python usse local maan leta hai. Agar assign se pehle read karo tohUnboundLocalErroraata hai! ✅ Fix:global countdeclare karo ya parameter pass karo.
Mistake 2: Built-in names ko shadow karna
Example
# ❌ BAD — built-in 'list' shadow ho gaya
list = [1, 2, 3]
try:
result = list("hello") # ❌ TypeError!
except TypeError as e:
print(f"Error: {e}")
# ✅ Fix — meaningful naam do
del list
my_list = [1, 2, 3]
result = list("hello")
print(result)
Example
# OUTPUT:
Error: 'list' object is not callable
['h', 'e', 'l', 'l', 'o']
🔴 Problem:list,dict,str,type,idjaise built-in names ko variable naam mat do — yeh confusing bugs create karte hain!
Mistake 3: Loop variable ko local samajhna
python example
# ❌ Python mein for loop ka apna scope NAHI hota
def process():
for i in range(5):
pass
print(f"i after loop: {i}") # i abhi bhi accessible hai!
process()Example
# OUTPUT:
i after loop: 4
🔴 Problem: C/Java ke opposite, Python mein for loop variable function scope mein hota hai, block scope nahi. Loop ke baad bhi accessible rehta hai!Mistake 4: Mutable global objects ko modify karna bina global ke
Example
# Mutable objects (list, dict) ko modify karna — global keyword ZARURI NAHI
scores = [90, 85, 78]
def add_score(score):
scores.append(score) # ✅ Works! Mutation, not reassignment
def reset_scores():
global scores
scores = [] # ✅ Reassignment ke liye global zaruri hai
add_score(95)
print(f"After add: {scores}")
reset_scores()
print(f"After reset: {scores}")
Example
# OUTPUT:
After add: [90, 85, 78, 95]
After reset: []
🔴 Confusion: Mutable object ko mutate karna (append, update) ke liyeglobalnahi chahiye. Lekin reassign karne ke liyeglobalzaruri hai!
Mistake 5: nonlocal ke jagah global use karna nested functions mein
python example
def outer():
count = 0
def inner():
nonlocal count # ✅ Enclosing scope ka variable
count += 1
return count
# ❌ Galat approach:
# def inner_wrong():
# global count # Yeh module-level dhundhega, outer ka nahi!
# count += 1
print(inner())
print(inner())
outer()Example
# OUTPUT:
1
2
🔴 Problem: Nested function mein enclosing variable modify karne ke liyenonlocaluse karo,globalnahi!
Mistake 6: Closure mein late binding ka trap
Example
# ❌ Classic closure trap — late binding
functions = []
for i in range(5):
functions.append(lambda: i) # Sab same 'i' ko reference karte hain
print("Late binding (wrong):", [f() for f in functions])
# ✅ Fix — default argument se capture karo
functions_fixed = []
for i in range(5):
functions_fixed.append(lambda x=i: x) # 'i' ki value capture ho gayi
print("Early binding (right):", [f() for f in functions_fixed])
Example
# OUTPUT:
Late binding (wrong): [4, 4, 4, 4, 4]
Early binding (right): [0, 1, 2, 3, 4]
🔴 Problem: Closures variables ki reference capture karte hain, value nahi! Loop mein lambda banate waqt default argument trick use karo.
Mistake 7: Function ke andar global declare karna aur same naam local variable banana
python example
x = "global"
def confusing():
# ❌ SyntaxError agar same function mein global + assignment before use
# Python compile time pe decide karta hai — local ya global
x = "local"
print(x)
confusing()
print(x) # Global x unchangedExample
# OUTPUT:
local
global
🔴 Tip: Ek hi function mein ek variable ya global hoga ya local — dono nahi ho sakta. Python compile-time pe decide karta hai!
✅ Key Takeaways
- 🎯 LEGB Rule — Python variables ko Local → Enclosing → Global → Built-in order mein dhundhta hai
- 🏠 Local Scope — Function ke andar banaye gaye variables sirf usi function mein accessible hain, bahar nahi
- 🌍 Global Scope — Module level pe defined variables poore file mein accessible hain, lekin modify karne ke liye
globalkeyword chahiye - 🔄
globalkeyword — Function ke andar global variable ko reassign karne ke liye use hota hai (read ke liye zaruri nahi) - 📦
nonlocalkeyword — Nested function mein enclosing scope ka variable modify karne ke liye use hota hai - 🎁 Closures — Inner function apne enclosing scope ke variables ki reference hold karta hai, even outer function return ho chuka ho
- ⚡ Mutable vs Immutable — Mutable globals (list, dict) ko mutate karna bina
globalke possible hai, lekin reassign ke liyeglobalzaruri - 🚫 Built-in shadow mat karo —
list,dict,str,typejaise names ko variable naam mat do - 🔁 Loop variables — Python mein for loop ka apna block scope nahi hota, variable function scope mein rehta hai
- 📝 Best Practice — Global variables kam se kam use karo, function parameters aur return values prefer karo
❓ FAQ
Q1: Scope aur Namespace mein kya difference hai?
🅰️ Namespace ek dictionary hai jo names ko objects se map karta hai (jaise {'x': 10, 'name': 'Rahul'}). Scope ek region hai code ka jahan se ek particular namespace directly accessible hai. Simple words mein: Namespace kya store hai, Scope kahan se access ho sakta hai!Q2: Kya if/else ya for loop ka apna scope hota hai Python mein?
🅰️ Nahi! Python mein sirf functions, classes, aur modules ka apna scope hota hai.if,for,while,tryblocks ka alag scope NAHI hota — yeh enclosing function/module scope use karte hain. Isliye loop variable baad mein bhi accessible rehta hai!
Q3: global keyword kab use karna chahiye?
🅰️ Jab aapko function ke andar se module-level variable ko reassign karna ho tab. Lekin best practice yeh hai ki global variables kam use karo — function parameters aur return values prefer karo. Global state debugging mushkil bana deta hai! 🐛
Q4: nonlocal keyword global scope pe kaam karta hai?
🅰️ Nahi!nonlocalsirf enclosing function scope pe kaam karta hai. Module-level (global) variable ke liyeglobaluse karo. Agar koi enclosing function nahi hai tohnonlocaluse karne peSyntaxErroraayega!
Q5: Closure kab use karna chahiye?
🅰️ Closures useful hain jab: - Aapko factory functions banana ho (jaisemake_counter(),make_validator()) - Data hiding/encapsulation chahiye bina class ke - Decorators likhnein ho (decorators closures pe based hote hain!) - Configuration ya state hold karni ho across multiple calls
Q6: Kya class ke andar ka scope LEGB rule follow karta hai?
🅰️ Partially! Class body ka apna scope hota hai, lekin yeh LEGB mein Enclosing ki tarah nahi kaam karta. Class ke methods mein class variables ko access karne ke liyeself.variableyaClassName.variableuse karna padta hai. Direct naam se access nahi hota class body ke bahar!
Q7: Multiple global declarations allowed hain ek function mein?
🅰️ Haan! Aap ek function mein multiple global variables declare kar sakte ho: ``python def func(): global x, y, z # Ek line mein multiple x, y, z = 1, 2, 3 `` Lekin zyada globals ka matlab hai code refactor karne ki zarurat hai! 🛠️Q8: Variable ki lifetime (lifespan) kya hoti hai?
🅰️ Local variables — Function call start se end tak (return/exception pe destroy) Global variables — Module load hone se program end tak Enclosing variables (closures) — Jab tak closure object alive hai tab tak survive karte hain!
🎯 Interview Questions
IQ1: LEGB rule ko explain karo with example.
Answer: LEGB rule Python ka scope resolution order hai: - L (Local): Function ke andar defined variables - E (Enclosing): Outer/enclosing functions ke variables (nested functions mein) - G (Global): Module level pe defined variables - B (Built-in): Python ke pre-defined names (print, len, etc.) Python pehle Local mein dhundhta hai, nahi mila toh Enclosing, phir Global, last mein Built-in. Agar kahin nahi mila toh NameError raise hota hai.IQ2: global aur nonlocal keywords mein kya fundamental difference hai?
Answer: -global— Module-level (top-level) variable ko function ke andar modify karne ke liye -nonlocal— Nearest enclosing function scope ka variable modify karne ke liye -globalkisi bhi function mein use ho sakta hai -nonlocalsirf nested functions mein hi valid hai — top-level function mein use karne pe SyntaxError aata hai
IQ3: UnboundLocalError kab aur kyun aata hai?
Answer: Jab Python compiler dekhta hai ki function mein kisi variable ko assign kiya gaya hai, toh woh us variable ko local maan leta hai (compile time pe). Ab agar assignment se pehle us variable ko read karo, tohUnboundLocalErroraata hai kyunki local variable abhi create nahi hua. ``python x = 10 def func(): print(x) # ❌ UnboundLocalError — x local hai but abhi defined nahi x = 20 # Is line ki wajah se x local ban gaya``
IQ4: Closure kya hai? Real-world use case batao.
Answer: Closure ek function hai jo apne enclosing scope ke variables ko remember karta hai even after outer function return ho chuka ho. Inner function outer function ke variables ki reference hold karta hai. Use Cases: - Factory functions (make_counter, make_multiplier) - Decorators (Python decorators closures pe based hain) - Data encapsulation without classes - Callback functions with state - Partial function application
IQ5: Python mein for loop ka apna scope kyun nahi hota?
Answer: Python mein sirf functions, classes, aur modules new scope create karte hain.for,while,if,tryblocks new scope nahi banate — yeh design decision hai. Loop variable enclosing function/module scope mein rehta hai. Yeh C/Java se different hai jahan blocks ka apna scope hota hai. ``python for i in range(3): pass print(i) # ✅ Works! Output: 2``
IQ6: globals() aur locals() functions kya return karte hain?
Answer: -globals()— Current module ka global namespace (dictionary) return karta hai. Isko modify karna global variables change karta hai. -locals()— Current local scope ka namespace (dictionary) return karta hai. Function ke andar isko modify karna guaranteed nahi hai ki actual local variables change hon. ``python x = 10 def func(): y = 20 print(locals()) # {'y': 20} print('x' in globals()) # True``
IQ7: Variable shadowing kya hai? Isse avoid kaise karo?
Answer: Variable shadowing tab hoti hai jab inner scope mein same naam ka variable bana dete ho jo outer scope mein already exist karta hai. Inner scope ka variable outer wale ko hide (shadow) kar deta hai. Avoid karne ke liye: - Unique, descriptive variable names use karo - Built-in names (list, dict, str, type) se bachke rahein - Linters (pylint, flake8) use karo jo shadowing warnings dete hain
IQ8: Closure mein late binding kya hai? Isse kaise fix karte hain?
Answer: Closures variables ki reference capture karte hain, value nahi. Loop mein closures banate waqt sab closures same variable ki last value dekhte hain — isse late binding kehte hain. ``python # ❌ Problem funcs = [lambda: i for i in range(3)] print([f() for f in funcs]) # [2, 2, 2] # ✅ Fix — default argument funcs = [lambda x=i: x for i in range(3)] print([f() for f in funcs]) # [0, 1, 2] ``IQ9: Python mein class scope LEGB rule mein kahan fit hota hai?
Answer: Class scope LEGB rule ka direct part nahi hai. Class body ka apna namespace hota hai, lekin yeh methods ke liye enclosing scope ki tarah kaam nahi karta. Methods mein class attributes access karne ke liyeself.attryaClassName.attruse karna padta hai. ``python class MyClass: x = 10 def method(self): # print(x) # ❌ NameError! print(self.x) # ✅ Works print(MyClass.x) # ✅ Works``
IQ10: global keyword use karne ki jagah better alternatives kya hain?
Answer: Global variables se bachne ke alternatives: 1. Function parameters + return values — Data flow explicit ho 2. Classes — State ko object mein encapsulate karo 3. Closures — Data hiding with enclosing scope 4. Module-level constants (UPPER_CASE) — Read-only config 5. Dependency injection — Functions ko dependencies pass karo Global mutable state debugging, testing, aur concurrency mein problems create karta hai!
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Scope of Variables in Python.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, functions, scope, variables
Related Python Master Course Topics
Continue learning this concept
FunctionsDecorators in PythonDetailed guide to Python decorators — function decorators, class decorators, stacking, functools.wraps, and real-world use cases. Learn with examples and best practices.FunctionsFunction Arguments in PythonComplete guide to Python function arguments — positional, keyword, default, *args, **kwargs and their real-world use cases. Understand argument types with best practices.FunctionsFunctions Basics in PythonPython mein functions ki complete guide — definition, calling, types, aur best practices. Samjho functions ka syntax, purpose, aur real-world usage Hindi explanations ke saath.FunctionsGenerators in PythonPython generators ki detailed guide — yield keyword, generator functions, generator expressions, send/throw/close, aur real-world use cases jaise infinite sequences, data pipelines, aur memory-efficient file processing. Hindi mein.FunctionsLambda Functions in PythonComplete guide to Python lambda functions — syntax, use cases, usage with map/filter/sorted, and comparison with regular functions. Learn with practical examples.FunctionsRecursive Functions in PythonPython mein recursion ki complete guide — base case, recursive case, call stack, fibonacci, factorial, binary search aur tree traversal ke saath Hindi explanations.