Code Explanation:
Line 1: def outer():
Defines a function named outer(). The code inside it runs when outer() is called.
Line 2: x = 5
Creates a local variable x and assigns it the value 5.
Current value:
x = 5
Line 3: def inner():
Defines another function named inner() inside outer(). This is called a nested function.
Line 4: return x + 2
The inner function returns the value of x + 2.
Important: Python looks up the value of x when inner() executes. It does not permanently capture the initial value 5.
Line 5: x = 10
Changes the local variable x from 5 to 10.
Current value:
x = 10
This happens before inner() is called.
Line 6: return inner()
Calls the inner function and returns its result.
Since x is now 10, the calculation is:
\[
10 + 2 = 12
\]
Therefore, inner() returns 12, and outer() returns 12.
Line 7: print(outer())
Calls outer() and prints the value it returns.
3. Execution Flow
Step 1: x = 5
Step 2: Define inner()
Step 3: Update x = 10
Step 4: inner() calculates 10 + 2
Output: 12
4. Final Output
12


0 Comments:
Post a Comment