Step-by-Step Execution
Define outer() function
- Inside outer(), a variable x is initialized with the value 2.
- inner() is defined inside outer() and modifies x using nonlocal.
Define inner() function
- inner() accesses the x variable from outer() using nonlocal.
- The x *= 2 operation doubles the value of x.
- inner() returns the updated value of x.
Return the inner() function
- When outer() is called, it returns inner() instead of executing it immediately.
Execution of closure = outer()
- outer() is executed, and inner() is returned.
- The x variable remains inside the closure and is remembered.
First Call: print(closure())
- inner() is called.
- x = 2 (from outer()).
- x *= 2 → Now x = 4.
- Returns 4, so it prints 4.
Second Call: print(closure())
- inner() is called again.
- x = 4 (previously modified value).
- x *= 2 → Now x = 8.
- Returns 8, so it prints 8.
Final Output
Key Concepts Used
- Closure: The function inner() remembers the variable x from outer(), even after outer() has finished execution.
- nonlocal keyword: This allows inner() to modify x in outer(), instead of creating a new local variable.
- State Retention: The value of x persists between function calls.
0 Comments:
Post a Comment