0
0
Pythonprogramming~10 mins

Enclosing scope in Python - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Enclosing scope
Define outer function
Define inner function
Inner function accesses outer variable
Call inner function
Use outer variable from inner function
Shows how an inner function can use variables from its outer function's scope.
Execution Sample
Python
def outer():
    x = 10
    def inner():
        return x + 5
    return inner()

result = outer()
Defines an outer function with a variable x, an inner function that uses x, and calls inner to get result.
Execution Table
StepActionVariable xInner function returnResult variable
1Call outer()x not setN/AN/A
2Set x = 10 in outer10N/AN/A
3Define inner() inside outer10N/AN/A
4Call inner()10x + 5 = 15N/A
5inner() returns 151015N/A
6outer() returns 15101515
7Assign result = outer()101515
💡 outer() finishes and returns inner() result, assigned to result
Variable Tracker
VariableStartAfter Step 2After Step 4After Step 6Final
xundefined10101010
Inner function returnN/AN/A151515
resultundefinedundefinedundefined1515
Key Moments - 2 Insights
Why can inner() access variable x even though x is not defined inside inner()?
Because inner() is inside outer(), it can use variables from outer()'s scope as shown in step 4 of the execution_table.
What happens if outer() is called multiple times? Does x keep its value?
Each call to outer() creates a new x variable, so x is reset to 10 every time outer() runs, as seen in step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of x when inner() is called at step 4?
A10
B5
Cundefined
D15
💡 Hint
Check the 'Variable x' column at step 4 in the execution_table.
At which step does the inner function return its value?
AStep 3
BStep 5
CStep 4
DStep 6
💡 Hint
Look at the 'Inner function return' column in the execution_table.
If we change x to 20 in outer(), what will be the inner() return value?
A15
B10
C25
D20
💡 Hint
Recall inner() returns x + 5; see variable_tracker for how x affects the return.
Concept Snapshot
Enclosing scope means an inner function can use variables from its outer function.
Syntax: define inner inside outer, inner accesses outer's variables.
The inner function remembers outer's variables when called.
Useful for organizing code and closures.
Example: inner() returns x + 5 where x is from outer().
Full Transcript
This example shows how an inner function can access a variable defined in its outer function. When outer() is called, it sets x to 10 and defines inner(). Calling inner() returns x + 5, which is 15. The result is returned by outer() and stored in result. The variable x is accessible inside inner() because of the enclosing scope. Each call to outer() creates a new x. This helps organize code and share data between nested functions.