📑 Table of Contents — किसी भी topic पर सीधे जाएँ
Scope क्या है? — Variable का घर व उम्र
def show():
x = 100 # yah variable yahi "paida" hota hai
print("Andar:", x)
show()
# function khatm hote hi x memory se GAYAB!
# print(x) # NameError aayegiLEGB Rule — Python किस क्रम में नाम ढूँढता है
LEGB — घोंसले के अंदर घोंसला (सबसे अंदर पहले खोजा जाता है)
x = "Global X" # G
def outer():
x = "Enclosing X" # E
def inner():
x = "Local X" # L
print(x) # sabse pehle YAHI milega
inner()
outer()
print(len("Python")) # B — built-in function6
def outer():
message = "Hello from outer" # Enclosing ke liye
def inner():
print(message) # Local me nahi mila -> Enclosing me dekha
inner()
outer()global व nonlocal Keywords — बाहर का Variable बदलना
x = 50
def update():
global x
x = 200
print("Andar:", x)
update()
print("Bahar:", x)Bahar: 200
def outer():
x = "outer value"
def inner():
nonlocal x # global nahi, outer function ka x
x = "modified by inner"
print("Inner:", x)
inner()
print("Outer:", x) # yah bhi badal gaya!
outer()Outer: modified by inner
⚖️ global vs nonlocal — पूरी तुलना
| आधार | global | nonlocal |
|---|---|---|
| किसे target करता है | सबसे बाहरी (module-level) variable | बीच वाले outer function का variable |
| कहाँ उपयोग | किसी भी function के अंदर | सिर्फ nested (अंदर के) function में |
| बिना keyword | UnboundLocalError | UnboundLocalError |
Modules क्या हैं? — हर .py File एक Module है
.py file है जिसमें functions/variables हों, जिसे import करके दूसरी files में उपयोग किया जा सके।# file: mymodule.py
def greet(name):
print("Namaste,", name)
x = 100import mymodule
mymodule.greet("Aditya")
print("x =", mymodule.x)x = 100
📦 Import के 3 तरीके (Chapter 6 का recap + विस्तार)
import mymodule # poora module — prefix zaroori from mymodule import greet, x # sirf selected members from mymodule import * # sab kuch (⚠ avoid — conflicts ho sakte hain)
🎯 __name__ == "__main__" — बहुत Important Pattern
# file: demo.py
def show():
print("Inside demo module")
if __name__ == "__main__":
print("Yah file directly chal rahi hai")
else:
print("Yah kisi aur file me import hui hai")python demo.py से direct चलाते हैं — __name__ = "__main__"। जब कोई और file import demo करती है — __name__ = "demo"। इसी check से हम decide करते हैं कि कोड सिर्फ direct-run होने पर चले, import होने पर नहीं।Modules as Namespaces — हर Module का अपना कमरा
दो Modules — Same नाम, अलग Namespace, कोई टकराव नहीं
# mod1.py: x = 10 # mod2.py: x = 50 import mod1 import mod2 print(mod1.x) # 10 print(mod2.x) # 50 — koi confusion nahi!
50
import math print(dir(math)[:5]) # pehle 5 names dekhte hain
Import Model — import लिखते ही अंदर क्या होता है?
import module_name लिखते हैं, Python एक पूरा internal process चलाता है — यह देखिए step-by-step।Import Process — import लिखने से module तैयार होने तक
import sys print(sys.path[0]) # pehla search path (aksar current directory) print(len(sys.path)) # kitne paths hain
import sys
import math
print("math" in sys.modules) # True — pehle se load ho chuka
import math # DOBARA import — file dobara nahi padhi jaati
print("Fast! Cached version use hua")Fast! Cached version use hua
try:
import unknown_module
except ModuleNotFoundError:
print("Module nahi mila!")Module Reloading — बिना Restart किए Update लाना
import module को सिर्फ पहली बार load करता है — दोबारा import करने पर पुराना cached version ही मिलता है। Module file में बदलाव के बाद नया version लाने के लिए importlib.reload() उपयोग करते हैं।import mymodule
mymodule.greet() # "Hello from Version 1"
# ...ab mymodule.py file me badlaav kiya gaya...
# def greet(): print("Hello from Version 2")
import importlib
importlib.reload(mymodule)
mymodule.greet() # "Hello from Version 2" — naya code aa gaya!Hello from Version 2
⚠️ कब उपयोगी है, कब सावधानी बरतें
- ✅ Jupyter/IDLE जैसे long-running sessions में testing के दौरान।
- ✅ किसी module file में change करने के बाद बिना restart किए test करना।
- ⚠️ Reload से पुराने global variables reset हो सकते हैं — सावधानी से उपयोग करें।
🎯 Output-Based Questions — Scope व Modules के Tricky सवाल
Q1. LEGB — Local जीतता है
x = "global"
def f():
x = "local"
print(x)
f()
print(x)global
← function के अंदर local x जीता; बाहर global x वैसा ही रहा।
Q2. Enclosing Scope Access
def outer():
y = "outer y"
def inner():
print(y) # local me nahi, enclosing me hai
inner()
outer()← inner में y नहीं है — Python Enclosing scope में देखकर मिल गया।
Q3. global Keyword का असर
count = 5
def inc():
global count
count += 1
inc()
inc()
print(count)← दोनों calls में global count असली बदला — 5→6→7।
Q4. nonlocal बनाम बिना keyword
def outer():
n = 10
def inner():
n = 20 # nonlocal NAHI hai — yah NAYA local n hai
print("Inner:", n)
inner()
print("Outer:", n)
outer()Outer: 10
← nonlocal न होने से inner का n बिल्कुल अलग local variable है — outer वाला अछूता रहा।
Q5. Module Namespace — कोई Conflict नहीं
import mod1, mod2 print(mod1.x + mod2.x)
← दोनों x अलग namespace में — mod1.x=1, mod2.x=2, sum=3।
Q6. __name__ Check
if __name__ == "__main__":
print("Direct run")
else:
print("Imported")← Directly चलाने पर __name__ हमेशा "__main__" होता है।
💻 Practice Programs — Scope व Modules के असली उपयोग
Program 1 — Counter (global keyword का practical उपयोग)
visitors = 0
def new_visitor():
global visitors
visitors += 1
print(f"Visitor #{visitors} aaya!")
new_visitor()
new_visitor()
new_visitor()
print("Total visitors:", visitors)Visitor #2 aaya!
Visitor #3 aaya!
Total visitors: 3
Program 2 — Counter Generator (nonlocal से closure)
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
my_counter = make_counter()
print(my_counter())
print(my_counter())
print(my_counter())2
3
Program 3 — अपना Utility Module बनाना
# File: shape_utils.py
def rectangle_area(l, w):
return l * w
def circle_area(r):
return 3.14159 * r * r
if __name__ == "__main__":
print("Testing shape_utils directly")
# File: main.py
import shape_utils
print(shape_utils.rectangle_area(5, 3))
print(shape_utils.circle_area(4))50.26544
Program 4 — Module से Available Functions देखना
import random
functions = [name for name in dir(random) if not name.startswith("_")]
print("Total public functions:", len(functions))
print("Kuch functions:", functions[:5])Kuch functions: ['BPF', 'LOG4', 'NV_MAGICCONST', ...]
Summary — Quick Revision (Exam से पहले पढ़ें)
- Scope = variable कहाँ accessible; Lifetime = कब तक memory में रहता है।
- LEGB Rule: Local → Enclosing → Global → Built-in — इसी क्रम में Python नाम ढूँढता है, जहाँ मिले वहीं रुक जाता है।
- global keyword — module-level variable को function के अंदर से modify करने के लिए; nonlocal — outer (enclosing) function के variable को nested function से modify करने के लिए।
- Module = .py file जिसे import करके उपयोग करें; import module, from module import x, import module as alias — 3 तरीके।
- __name__ == "__main__" — बताता है file direct चली या import हुई; module को dual-purpose बनाने की trick।
- Namespace = names का mapping; हर module का अपना independent namespace — same नाम के variable दो modules में बिना conflict के रह सकते हैं।
- Import process: sys.modules check → sys.path search → .pyc compile → memory load → sys.modules register। दोबारा import cached version उपयोग करता है।
- Module Reloading: importlib.reload(module) — बिना restart किए updated code लाने के लिए।
Model Questions — 50 MCQs + 15 Theory Questions
❓ A. Multiple Choice Questions (50)
| # | प्रश्न |
|---|---|
| 1 | LEGB का पूरा नाम है — (a) Local Enclosing Global Built-in(b) Local Extended Global Basic(c) Level Encoding General Basic(d) Local Enclosed Generic Built-in ✔ सही उत्तर: (a) Local Enclosing Global Built-inPython variable search का क्रम। |
| 2 | LEGB में सबसे पहले कौन-सा scope check होता है? (a) Global(b) Built-in(c) Local(d) Enclosing ✔ सही उत्तर: (c) Localसबसे अंदर वाला scope पहले। |
| 3 | LEGB में सबसे आखिर में कौन-सा scope check होता है? (a) Local(b) Enclosing(c) Global(d) Built-in ✔ सही उत्तर: (d) Built-inlen(), print() जैसे predefined names। |
| 4 | Nested function में outer function का scope कहलाता है — (a) Local(b) Enclosing(c) Global(d) Built-in ✔ सही उत्तर: (b) Enclosing |
| 5 | किसी scope में नाम न मिले तो Python क्या करता है? (a) 0 return करता है(b) अगले scope में खोजता है(c) None return करता है(d) Program रुक जाता है ✔ सही उत्तर: (b) अगले scope में खोजता हैसभी scopes में न मिले तो NameError। |
| 6 | Module-level variable modify करने वाला keyword — (a) local(b) global(c) nonlocal(d) static ✔ सही उत्तर: (b) global |
| 7 | Nested function से outer function का variable modify करने वाला keyword — (a) global(b) nonlocal(c) outer(d) enclosing ✔ सही उत्तर: (b) nonlocal |
| 8 | global keyword के बिना variable modify करने पर आती है — (a) SyntaxError(b) UnboundLocalError(c) TypeError(d) कोई error नहीं ✔ सही उत्तर: (b) UnboundLocalError |
| 9 | nonlocal keyword किस scope तक पहुँच सकता है? (a) सीधे Global तक(b) सिर्फ enclosing (outer) function तक(c) Built-in तक(d) कहीं नहीं ✔ सही उत्तर: (b) सिर्फ enclosing (outer) function तकGlobal तक जाने के लिए global keyword चाहिए। |
| 10 | Local व Global variable same नाम के हों तो function के अंदर कौन प्राथमिकता पाता है? (a) Global(b) Local(c) दोनों merge(d) Error ✔ सही उत्तर: (b) Local |
| 11 | Module क्या है? (a) एक function(b) .py file जिसमें code हो(c) एक variable(d) एक loop ✔ सही उत्तर: (b) .py file जिसमें code हो |
| 12 | Module import करने का सही तरीका — (a) include module(b) import module(c) load module(d) using module ✔ सही उत्तर: (b) import module |
| 13 | Module को alias देने का keyword — (a) rename(b) as(c) alias(d) named ✔ सही उत्तर: (b) asimport module as alias। |
| 14 | from module import * क्यों avoid करना चाहिए? (a) Slow होता है(b) Namespace conflicts हो सकते हैं(c) Error देता है हमेशा(d) कोई कारण नहीं ✔ सही उत्तर: (b) Namespace conflicts हो सकते हैं |
| 15 | File को direct चलाने पर __name__ की value — (a) module का नाम(b) "__main__"(c) खाली string(d) None ✔ सही उत्तर: (b) "__main__" |
| 16 | Module को import करने पर उसके अंदर __name__ की value — (a) "__main__"(b) module का नाम(c) खाली string(d) None ✔ सही उत्तर: (b) module का नाम |
| 17 | Namespace क्या है? (a) एक loop(b) names व उनकी values का mapping(c) एक function(d) एक operator ✔ सही उत्तर: (b) names व उनकी values का mapping |
| 18 | दो अलग modules में same नाम के variable होने पर — (a) Error आती है(b) कोई conflict नहीं (अलग namespace)(c) दोनों merge हो जाते हैं(d) Program crash होता है ✔ सही उत्तर: (b) कोई conflict नहीं |
| 19 | Module के सारे names देखने का function — (a) list()(b) dir()(c) show()(d) names() ✔ सही उत्तर: (b) dir()dir(module_name)। |
| 20 | Module का namespace dictionary रूप में देखने वाला attribute — (a) __dict__(b) __name__(c) __doc__(d) __file__ ✔ सही उत्तर: (a) __dict__ |
| 21 | Import करने पर Python सबसे पहले क्या check करता है? (a) sys.path(b) sys.modules (पहले से loaded?)(c) file size(d) internet connection ✔ सही उत्तर: (b) sys.modules |
| 22 | sys.path क्या है? (a) Loaded modules की list(b) Module search directories की list(c) Error messages की list(d) Function names की list ✔ सही उत्तर: (b) Module search directories की list |
| 23 | sys.modules क्या है? (a) Search paths की list(b) पहले से loaded modules की dictionary(c) Error codes(d) Function list ✔ सही उत्तर: (b) पहले से loaded modules की dictionary |
| 24 | Module को compile करके किस format में बदला जाता है? (a) .exe(b) .pyc (bytecode)(c) .txt(d) .html ✔ सही उत्तर: (b) .pyc (bytecode) |
| 25 | .pyc files कहाँ store होती हैं? (a) sys folder(b) __pycache__ folder(c) root directory(d) कहीं नहीं ✔ सही उत्तर: (b) __pycache__ folder |
| 26 | Module दोबारा import करने पर क्या होता है? (a) फिर से पूरी file पढ़ी जाती है(b) Cached version (sys.modules से) उपयोग होता है(c) Error आती है(d) Module delete हो जाता है ✔ सही उत्तर: (b) Cached version उपयोग होता हैइसीलिए दोबारा import तेज़ होता है। |
| 27 | Module न मिलने पर आने वाली exception — (a) FileNotFoundError(b) ModuleNotFoundError(c) ImportError only(d) ValueError ✔ सही उत्तर: (b) ModuleNotFoundError |
| 28 | Module को reload करने के लिए function — (a) reload()(b) importlib.reload()(c) refresh()(d) update() ✔ सही उत्तर: (b) importlib.reload() |
| 29 | importlib.reload() क्यों उपयोग होता है? (a) Module delete करने के लिए(b) बिना restart किए updated code लाने के लिए(c) Module का नाम बदलने के लिए(d) Error रोकने के लिए ✔ सही उत्तर: (b) बिना restart किए updated code लाने के लिए |
| 30 | Normal import दोबारा करने पर module reload होता है क्या? (a) हाँ, हमेशा(b) नहीं, cached version उपयोग होता है(c) सिर्फ पहली बार(d) Random ✔ सही उत्तर: (b) नहीं, cached version उपयोग होता है |
| 31 | x = 10; def f(): print(x) — Output? (a) 10(b) Error(c) None(d) 0 ✔ सही उत्तर: (a) 10बिना modify किए global variable पढ़ने में कोई keyword नहीं चाहिए। |
| 32 | Local scope का lifetime कब खत्म होता है? (a) Program शुरू होते ही(b) Function समाप्त होते ही(c) कभी नहीं(d) File save होते ही ✔ सही उत्तर: (b) Function समाप्त होते ही |
| 33 | Built-in scope में क्या आता है? (a) User की बनाई functions(b) len(), print() जैसे Python predefined names(c) Global variables(d) Local variables ✔ सही उत्तर: (b) len(), print() जैसे predefined names |
| 34 | globals() function क्या return करता है? (a) सभी local variables(b) सभी global variables (dictionary)(c) सिर्फ functions(d) कुछ नहीं ✔ सही उत्तर: (b) सभी global variables (dictionary) |
| 35 | locals() function क्या return करता है? (a) Current scope के local variables(b) Global variables(c) Built-in functions(d) File names ✔ सही उत्तर: (a) Current scope के local variables |
| 36 | from math import sqrt करने के बाद उपयोग — (a) math.sqrt(16)(b) sqrt(16)(c) sqrt.math(16)(d) import.sqrt(16) ✔ सही उत्तर: (b) sqrt(16)Prefix की ज़रूरत नहीं। |
| 37 | import math as m के बाद उपयोग — (a) math.sqrt()(b) m.sqrt()(c) sqrt()(d) as.sqrt() ✔ सही उत्तर: (b) m.sqrt() |
| 38 | Custom module (mymodule.py) import करने का तरीका — (a) import mymodule.py(b) import mymodule(c) load mymodule(d) include mymodule ✔ सही उत्तर: (b) import mymoduleबिना .py extension के। |
| 39 | Enclosing scope तभी होता है जब — (a) कोई भी function हो(b) Function nested (function के अंदर function) हो(c) Module import हो(d) Loop चल रहा हो ✔ सही उत्तर: (b) Function nested हो |
| 40 | nonlocal keyword बिना enclosing function के उपयोग करने पर — (a) SyntaxError(b) कुछ नहीं होता(c) global जैसा काम करता है(d) TypeError ✔ सही उत्तर: (a) SyntaxErrornonlocal सिर्फ nested function में valid है। |
| 41 | Module में documentation string access करने के लिए — (a) module.__name__(b) module.__doc__(c) module.__file__(d) module.__init__ ✔ सही उत्तर: (b) module.__doc__ |
| 42 | Built-in module का उदाहरण — (a) mymodule(b) math(c) shape_utils(d) userfile ✔ सही उत्तर: (b) mathPython के साथ पहले से आता है। |
| 43 | Python interpreter modules किस order में खोजता है? (a) Random order(b) Current directory → PYTHONPATH → Standard library(c) सिर्फ standard library(d) सिर्फ current directory ✔ सही उत्तर: (b) Current directory → PYTHONPATH → Standard library |
| 44 | Closure (जैसे make_counter उदाहरण) में क्या उपयोग होता है? (a) global(b) nonlocal(c) static(d) local ✔ सही उत्तर: (b) nonlocalInner function outer की value याद रखता व बदलता है। |
| 45 | दो बार global x += 1 करने पर x का increase — (a) 1(b) 2(c) 0(d) निर्भर करता है ✔ सही उत्तर: (b) 2हर call से 1 बढ़ता है, दो calls = 2 बार। |
| 46 | Module import होते समय उसका top-level code — (a) कभी नहीं चलता(b) एक बार चलता है(c) हर बार import पर चलता है(d) सिर्फ error पर चलता है ✔ सही उत्तर: (b) एक बार चलता हैपहले import पर; बाद में cache से। |
| 47 | Function के lifetime का संबंध किससे है? (a) File के नाम से(b) Function के call व return से(c) Variable के type से(d) Module के नाम से ✔ सही उत्तर: (b) Function के call व return से |
| 48 | Scope resolution की गलती से आने वाली आम error — (a) SyntaxError(b) NameError(c) IndexError(d) TypeError ✔ सही उत्तर: (b) NameErrorसभी LEGB scopes में न मिलने पर। |
| 49 | Module reload करने पर पुराने global variables का क्या होता है? (a) हमेशा सुरक्षित रहते हैं(b) Reset हो सकते हैं(c) Delete हो जाते हैं हमेशा(d) कोई असर नहीं ✔ सही उत्तर: (b) Reset हो सकते हैंइसीलिए reload सावधानी से उपयोग करें। |
| 50 | Modules व Namespaces की सबसे बड़ी उपयोगिता — (a) Program को धीमा बनाना(b) Code organize करना व naming conflicts से बचाना(c) Memory बढ़ाना(d) Syntax कठिन बनाना ✔ सही उत्तर: (b) Code organize करना व naming conflicts से बचाना |
📝 B. 15 Theory Questions (Short Answers)
- Scope व Lifetime में अंतर बताइए।Scope बताता है variable कहाँ accessible है (कौन-से हिस्से में); Lifetime बताता है variable memory में कब तक रहता है — दोनों जुड़े हैं पर अलग concept हैं।
- LEGB Rule क्या है? पूरा क्रम लिखिए।Python किसी नाम को खोजने का क्रम — Local (function के अंदर) → Enclosing (outer function) → Global (module-level) → Built-in (Python predefined)। जहाँ पहले मिले, वहीं रुक जाता है।
- global keyword की ज़रूरत कब पड़ती है?जब function के अंदर किसी module-level (global) variable की value बदलनी हो — बिना global keyword के Python उसे नया local variable मान लेता है और UnboundLocalError देता है।
- nonlocal keyword क्या करता है? global से कैसे अलग है?nonlocal nested function से outer (enclosing) function के variable को modify करने देता है — सिर्फ बीच वाले scope तक पहुँचता है, module-level तक नहीं (वहाँ तक global चाहिए)।
- Module क्या है? उदाहरण दीजिए।Module एक .py file है जिसमें functions, variables, classes हों — इसे import करके दूसरी files में उपयोग किया जा सकता है। उदाहरण: math, random, या खुद बनाई mymodule.py।
- Import के 3 तरीके लिखिए।import module_name (पूरा module, prefix चाहिए); from module_name import x (specific member, prefix नहीं चाहिए); import module_name as alias (छोटा नाम)।
- __name__ == "__main__" पैटर्न क्यों उपयोगी है?यह बताता है कि file directly चलाई गई है या किसी और file में import हुई है। इस check से एक ही file को standalone script व reusable module दोनों तरह उपयोग कर सकते हैं।
- Namespace क्या है?Names व उनकी values (objects) का mapping — एक dictionary जैसा। हर module, function का अपना namespace होता है, जिससे same नाम के variables बिना टकराए रह सकते हैं।
- दो modules में same नाम के variable हों तो क्या होगा?कोई conflict नहीं होगा क्योंकि हर module का अपना independent namespace है — उन्हें module_name.variable_name से अलग-अलग access करते हैं (जैसे mod1.x और mod2.x)।
- dir() function का उपयोग समझाइए।dir(module_name) module में मौजूद सभी names (functions, variables, classes) की list देता है — किसी भी module को explore करने का तरीका।
- Import होने पर Python अंदर क्या steps करता है?पहले sys.modules में check (पहले से loaded?) → नहीं तो sys.path directories में search → module मिलने पर .pyc bytecode में compile → memory में load → sys.modules में register।
- sys.path और sys.modules में अंतर बताइए।sys.path — directories की list जहाँ Python modules खोजता है (search paths)। sys.modules — पहले से load हो चुके modules की dictionary (cache)।
- Module reloading क्यों ज़रूरी होती है? कैसे करते हैं?Development/testing के दौरान module file में बदलाव के बाद updated code लाने के लिए — बिना Python restart किए। importlib.reload(module_name) से।
- globals() और locals() function क्या करते हैं?globals() current module के सभी global variables को dictionary में देता है; locals() current function के local variables dictionary में देता है — दोनों debugging में उपयोगी।
- Same function नाम दो modules में हो तो कैसे handle करते हैं?दोनों modules import करके module_name.function_name() से अलग-अलग call करते हैं — जैसे greet1.hello() और greet2.hello() — namespace अलग होने से कोई टकराव नहीं होता।