0
0
Pythonprogramming~10 mins

Enclosing scope in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to print the value of the outer variable inside the inner function.

Python
def outer():
    x = 10
    def inner():
        print([1])
    inner()
outer()
Drag options to blanks, or click blank then click option'
A10
Bx
Cinner
Douter
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using the function name instead of the variable name.
Trying to print a variable not defined in the inner function.
2fill in blank
medium

Complete the code to modify the outer variable inside the inner function using the correct keyword.

Python
def outer():
    count = 0
    def inner():
        [1] count
        count += 1
        print(count)
    inner()
    inner()
outer()
Drag options to blanks, or click blank then click option'
Anonlocal
Bglobal
Clocal
Douter
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using global instead of nonlocal.
Not using any keyword and causing an error.
3fill in blank
hard

Fix the error in the code by completing the blank with the correct keyword to modify the outer variable.

Python
def counter():
    num = 5
    def increment():
        [1] num
        num += 2
        return num
    return increment()
print(counter())
Drag options to blanks, or click blank then click option'
Alocal
Bouter
Cglobal
Dnonlocal
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using global which causes an error here.
Not using any keyword causing an UnboundLocalError.
4fill in blank
hard

Fill both blanks to create a closure that remembers the value of start and adds step each time.

Python
def make_adder(start):
    step = 0
    def adder():
        nonlocal [1]
        [2] += 1
        return start + [2]
    return adder

add = make_adder(5)
print(add())
print(add())
Drag options to blanks, or click blank then click option'
Astep
Bstart
Ccount
Dadder
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using start instead of step.
Not declaring the variable as nonlocal.
5fill in blank
hard

Fill all three blanks to create a function that counts calls using an enclosing variable and returns the count.

Python
def call_counter():
    count = 0
    def counter():
        [1] count
        count [2] 1
        return [3]
    return counter

c = call_counter()
print(c())
print(c())
Drag options to blanks, or click blank then click option'
Anonlocal
B+=
Ccount
Dglobal
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using global instead of nonlocal.
Forgetting to return the updated count.