Recall & Review
beginner
What is the enclosing scope in Python?
The enclosing scope is the scope of a function that surrounds another nested function. It is the middle layer between the local scope of the inner function and the global scope.
Click to reveal answer
beginner
How does Python find a variable in nested functions?
Python looks for the variable first in the local scope, then in the enclosing scope (the outer function), then in the global scope, and finally in the built-in scope.
Click to reveal answer
intermediate
What keyword allows a nested function to modify a variable in the enclosing scope?
The
nonlocal keyword lets a nested function change a variable defined in its enclosing function's scope.Click to reveal answer
beginner
Example: What will this code print?
def outer():
x = 5
def inner():
print(x)
inner()
outer()It will print
5 because the inner function accesses the variable x from the enclosing scope of outer.Click to reveal answer
intermediate
Why can't a nested function modify a variable in the enclosing scope without
nonlocal?Without
nonlocal, assigning to a variable inside a nested function creates a new local variable, so the enclosing variable remains unchanged.Click to reveal answer
In Python, where does the enclosing scope refer to?
✗ Incorrect
The enclosing scope is the scope of the outer function that contains the nested function.
Which keyword allows a nested function to modify a variable in its enclosing scope?
✗ Incorrect
The
nonlocal keyword lets a nested function modify variables in the enclosing scope.What happens if you assign a value to a variable inside a nested function without using
nonlocal?✗ Incorrect
Assigning without
nonlocal creates a new local variable inside the nested function.In the nested function, if a variable is not found locally, where does Python look next?
✗ Incorrect
Python looks in the enclosing scope after the local scope before checking global or built-in scopes.
What will this code print?
def outer():
x = 10
def inner():
x = 20
print(x)
inner()
print(x)
outer()✗ Incorrect
The inner function prints 20 (its local x), but the outer x remains 10.
Explain what the enclosing scope is and how Python uses it when looking up variables in nested functions.
Think about the layers Python checks for a variable name.
You got /3 concepts.
Describe how to modify a variable in an enclosing scope from inside a nested function and why this requires a special keyword.
Consider what happens when you assign a value inside a nested function.
You got /3 concepts.