Code Explanation:
๐น 1. Defining the Outer Function
def outer():
✅ Explanation:
A function named outer() is created.
This function contains another function (inner()), making it a nested function.
Current structure:
outer()
│
└── inner()
๐น 2. Creating a Local Variable
x = 10
✅ Explanation:
A local variable x is created inside outer().
Current memory:
outer()
x = 10
This variable belongs only to the outer() function.
๐น 3. Defining the Inner Function
def inner():
✅ Explanation:
A new function named inner() is created inside outer().
Structure becomes:
outer()
x = 10
│
inner()
At this point, inner() is only defined, not executed.
๐น 4. Using nonlocal
nonlocal x
✅ Explanation:
The nonlocal keyword tells Python:
"Don't create a new variable named x. Use the x from the nearest enclosing function (outer())."
Without nonlocal:
x += 5
would try to create a new local variable and raise an error.
Visual:
inner()
│
nonlocal x
│
Uses x from outer()
๐น 5. Updating the Variable
x += 5
✅ Explanation:
Current value of x:
x = 10
Calculation:
10 + 5
New value:
x = 15
Memory after update:
outer()
x = 15
Notice:
No new variable is created.
The original x inside outer() is modified.
๐น 6. Calling inner()
inner()
✅ Explanation:
Python executes the inner() function.
Execution steps:
inner()
↓
nonlocal x
↓
x = x + 5
↓
x becomes 15
Current state:
outer()
x = 15
๐น 7. Printing the Value
print(x)
✅ Explanation:
Python prints the value of x inside outer().
Current value:
x = 15
Output:
15
๐น 8. Calling outer()
outer()
✅ Explanation:
This starts the execution of the outer() function.
Execution flow:
outer()
↓
x = 10
↓
inner()
↓
x = 15
↓
print(x)
↓
15
๐ฏ Final Output
15

0 Comments:
Post a Comment