1.2.31 · D3 · HinglishIntroduction to Programming (Python)

Worked examplesglobal and nonlocal keywords

2,290 words10 min read↑ Read in English

1.2.31 · D3 · Coding › Introduction to Programming (Python) › global and nonlocal keywords

Yeh note global and nonlocal keywords ka worked-examples companion hai. Parent note ne aapko do rules sikhaye the:

  1. Ek function ke andar kisi bhi jagah kisi naam ko assign karna usse local bana deta hai poore function body ke liye (yeh compile time pe decide hota hai).
  2. global module top level tak pahunchta hai; nonlocal nearest enclosing function tak pahunchta hai.

Yahan hum sirf har possible case ko run karte hain taaki koi bhi scenario aapko surprise na kare. Agar neeche koi word unfamiliar lage (scope, closure, rebind), toh parent note aur Scope and LEGB rule usse define karte hain — hum sirf unhi ko assume karte hain.


Scenario matrix

Is topic se jo bhi situation aa sakti hai woh is table ke ek cell mein hai. Neeche ke examples mein har ek tagged hai apne cell(s) ke saath, aur milke yeh sab poora fill karte hain.

# Case class Kya keyword chahiye? Kaunsa?
C1 Sirf outer variable padho (read-only) Nahi
C2 Ek module variable ko rebind karo Haan global
C3 Ek enclosing-function variable ko rebind karo Haan nonlocal
C4 Ek object (list/dict) ko mutate karo — naam pe = nahi Nahi
C5 Degenerate: pehle rebind, phir read, no keyword Crash hoga UnboundLocalError
C6 Wrong keyword: nonlocal ki jagah global Crash / miss SyntaxError ya galat var
C7 Zero enclosing scopes: module top / ek level pe nonlocal Crash hoga SyntaxError
C8 Deep nesting — nonlocal sirf nearest enclosing pick karta hai Haan nonlocal (nearest)
C9 Real-world word problem (shared counter / config) Haan global
C10 Exam twist: global ek module var create karta hai jo pehle tha hi nahi Haan global
Figure — global and nonlocal keywords

Example 1 — Sirf outer variable padho (C1)


Example 2 — Classic crash (C5)


Example 3 — Module variable ko rebind karo (C2)


Example 4 — Mutate karo, rebind mat karo (C4)


Example 5 — Closure with nonlocal (C3)


Example 6 — Wrong keyword: enclosing var ke liye global (C6)


Example 7 — nonlocal bina kisi enclosing scope ke (C7)


Example 8 — Deep nesting: nonlocal sirf nearest enclosing pick karta hai (C8)

Figure — global and nonlocal keywords

Example 9 — Real-world: shared config toggle (C9)


Example 10 — Exam twist: global ek naya module variable create karta hai (C10)


Recall Yeh kaunsa cell hai? Quick self-test
total = 0
def add(v):
    total += v
add(5)

Answer ::: Cell C5 — total += v total ko rebind karta hai, use local banata hai; RHS assignment se pehle use read karta hai → UnboundLocalError. global total se fix karo.

Connections

  • global and nonlocal keywords
  • Scope and LEGB rule
  • Functions in Python
  • Closures
  • Mutable vs Immutable objects
  • UnboundLocalError
  • Pure functions and side effects