WHAT is "scope"? The region of code where a name is visible/usable.
WHAT is a "namespace"? The actual dictionary mapping names → objects that backs a scope.
Imagine you ask "Where are my shoes?" You check your room first (Local), then your big brother's room (Enclosing), then the front hallway (Global), and finally the shoe shop that always has shoes (Built-in). You grab the first pair you find and stop looking.
But there's a trick: if you ever say "I'll put shoes HERE in my room" (shoes = ...), Python assumes the shoes are in your room for the whole day — so if you try to wear them before putting them there, you're standing barefoot and confused (that's the UnboundLocalError). Saying global is like telling everyone "I mean the hallway shoes, not mine."
Dekho, jab Python kisi variable ka naam padhta hai — maan lo x — to wo har jagah randomly nahi dhoondta. Uska ek fixed order hota hai: pehle Local (jis function ke andar ho), phir Enclosing (bahar wala function, agar nested ho), phir Global (file ke top level ke naam), aur last me Built-in (jaise len, print). Jis room me naam pehle mil jaaye, bas wahi use hota hai — Python aage dhoondna band kar deta hai. Isko yaad rakhne ka short form hai LEGB.
Sabse important twist yahi hai: LEGB sirf padhne (read) ke liye hai. Jaise hi function ke andar kahin bhi x = kuch likha, Python decide kar leta hai ki poore function me x ab Local hai. Isiliye count = count + 1 likhne par agar count global tha, to bhi UnboundLocalError aata hai — kyunki Python soch raha hai ki count local hai aur abhi tak usme kuch assign hua hi nahi.
Is problem ko theek karne ke liye do keywords hain. global count bolne se Python samajh jaata hai ki "bhai, yahan count matlab module wala global count, naya local mat banao." Aur nonlocal n bolne se enclosing (bahar wale) function ka n edit hota hai — ye closures me kaam aata hai. Yaad rakho: global = module scope (G), nonlocal = enclosing function (E). Dono alag hain.
Ek aur galat-fehmi clear kar lo: Python me for aur if blocks apna alag scope nahi banate (C/Java se ulta). Sirf functions, modules, aur comprehensions scope banate hain. Isliye for loop ke andar banaya variable bahar bhi accessible rehta hai. Ye chhoti baatein interviews aur bugs dono me bahut help karti hain.