0
0
Pythonprogramming~5 mins

Enclosing scope in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AThe scope of the outer function surrounding a nested function
BThe global scope of the program
CThe local scope inside the nested function
DThe built-in Python scope
Which keyword allows a nested function to modify a variable in its enclosing scope?
Anonlocal
Bglobal
Clocal
Denclose
What happens if you assign a value to a variable inside a nested function without using nonlocal?
AIt modifies the variable in the enclosing scope
BIt creates a new local variable inside the nested function
CIt causes a syntax error
DIt modifies the global variable
In the nested function, if a variable is not found locally, where does Python look next?
AGlobal scope
BBuilt-in scope
CIt raises an error immediately
DEnclosing scope
What will this code print?
def outer():
    x = 10
    def inner():
        x = 20
        print(x)
    inner()
    print(x)
outer()
A20 and 20
B10 and 10
C20 and 10
D10 and 20
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.