Code Explanation:
๐งฉ 1. Function Definition: outer
def outer():
This defines a function named outer.
It acts as an enclosing (parent) function.
๐ฆ 2. Variable Initialization
x = 10
A local variable x is created inside outer.
Initial value of x is 10.
๐ 3. Inner Function Definition
def inner():
A nested function named inner is defined inside outer.
It has access to variables of outer (like x).
๐ 4. Using nonlocal
nonlocal x
nonlocal means:
“Use the variable x from the nearest enclosing scope (outer function), not create a new one.”
Without nonlocal, modifying x would cause an error.
➕ 5. Modify the Variable
x += 5
Adds 5 to the existing value of x.
Since x is nonlocal, it updates the outer function’s x.
๐ 6. Return Updated Value
return x
Returns the updated value of x.
๐ค 7. Return Inner Function
return inner
The outer function returns the inner function itself, not its result.
This creates a closure (function + its environment).
๐ฏ 8. Create Function Instance
f = outer()
Calls outer(), which returns inner.
Now f becomes a reference to inner, with x = 10 preserved.
๐จ️ 9. Function Calls and Output
print(f(), f())
First Call: f()
x = 10
x += 5 → 15
Returns 15
Second Call: f()
x = 15 (value persists due to closure)
x += 5 → 20
Returns 20
✅ Final Output
15 20

0 Comments:
Post a Comment