0
0
Pythonprogramming~5 mins

Nonlocal keyword in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the nonlocal keyword do in Python?
It allows a function to modify a variable defined in its nearest enclosing scope that is not global.
Click to reveal answer
intermediate
Why can't you use global to modify variables in an enclosing function?
global only affects variables at the module (global) level, not variables inside enclosing functions. nonlocal is needed for enclosing function variables.
Click to reveal answer
beginner
Given this code snippet, what will be printed?
def outer():
    x = 5
    def inner():
        nonlocal x
        x = 10
    inner()
    print(x)
outer()
It will print 10 because inner() changes x in the enclosing outer() function using nonlocal.
Click to reveal answer
intermediate
What error occurs if you use nonlocal on a variable that doesn't exist in any enclosing scope?
Python raises a SyntaxError because nonlocal requires the variable to exist in an enclosing function scope.
Click to reveal answer
beginner
Can nonlocal be used to modify global variables?
No. nonlocal only works with variables in enclosing functions. Use global to modify global variables.
Click to reveal answer
What does the nonlocal keyword allow you to do?
AModify a global variable
BModify a variable in the nearest enclosing function scope
CCreate a new local variable
DDelete a variable
What happens if you use nonlocal on a variable not found in any enclosing scope?
APython raises a SyntaxError
BThe variable is created locally
CThe variable is created globally
DNothing happens
Which keyword should you use to modify a global variable inside a function?
Aenclosing
Blocal
Cnonlocal
Dglobal
In this code, what will be printed?
def outer():
    x = 1
    def inner():
        x = 2
    inner()
    print(x)
outer()
A2
BError
C1
DNone
Which of these is true about nonlocal?
AIt can only be used inside nested functions
BIt can be used anywhere in the program
CIt creates a new global variable
DIt deletes variables
Explain how the nonlocal keyword works with an example.
Think about nested functions and changing variables outside the inner function.
You got /3 concepts.
    What is the difference between nonlocal and global keywords?
    Consider where the variable lives: inside a function or at the module level.
    You got /3 concepts.