Back
+15 XP
Concept

Nested Functions & the nonlocal Keyword

Functions defined inside another function can read enclosing variables. To modify an outer variable without making it global, use the `nonlocal` keyword 🛡️.

python
def make_counter():
    count = 0
    def step():
        nonlocal count
        count += 1
        return count
    return step

counter = make_counter()
print(counter())  # 1 ⚡
print(counter())  # 2 🚀

# 32. Nested Functions & the nonlocal Keyword Functions defined inside another function can read enclosing variables. To modify an outer variable without making it global, use the `nonlocal` keyword 🛡️. ```python def make_counter(): count = 0 def step(): nonlocal count count += 1 return count return step counter = make_counter() print(counter()) # 1 ⚡ print(counter()) # 2 🚀 ``` Without `nonlocal`, assigning `count += 1` causes Python to treat `count` as a brand-new local variable inside `step()`, immediately raising `UnboundLocalError` when read before assignment. 🛑 --- ### Question What happens if an inner function modifies an outer variable without declaring `nonlocal`? 🧠 - [ ] a. Python raises an UnboundLocalError when accessing it before assignment 🛑 - [ ] b. It silently changes the variable in the global module scope - [ ] c. It automatically converts the integer into a thread-safe mutex 🔒 - [ ] d. It deletes the parent function stack frame permanently 💀 --- ### Challenge Write a function `tracker(start)` returning an inner function `add(val)` that uses `nonlocal` to accumulate `start += val` and returns `start`. Call `t = tracker(10)`, print `t(5)` and `t(20)`. 🎯 <details> <summary>Solution</summary> ```python def tracker(start): def add(val): nonlocal start start += val return start return add t = tracker(10) print(t(5)) print(t(20)) ``` </details>

Checkpoint

What happens if an inner function modifies an outer variable without declaring `nonlocal`? 🧠

Practice

Write a function `tracker(start)` returning an inner function `add(val)` that uses `nonlocal` to accumulate `start += val` and returns `start`. Call `t = tracker(10)`, print `t(5)` and `t(20)`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks