Skip to content
Foxipa
Code Completion 5 Challenges

Complete the Python scopes and namespaces code

Practice local name resolution, global rebinding, and nonlocal rebinding.

Beginner ~8 min read

Challenge 1

Complete the nested function so it prints the enclosing function value.

python Your answer
def outer():
    topic = "scopes"

    def inner():

    inner()

outer()

Press Ctrl⌘Enter to check your answer

Challenge 2

Declare count as a module-level binding so the function can increment it.

python Your answer
count = 0

def increase():
    count += 1

increase()
print(count)

Press Ctrl⌘Enter to check your answer

Challenge 3

Declare count as the enclosing function binding so next_count() can update it.

python Your answer
def make_counter():
    count = 0

    def next_count():
        count += 1
        return count

    return next_count

counter = make_counter()
print(counter())

Press Ctrl⌘Enter to check your answer

Challenge 4

Make the function read the module-level count without assigning to it.

python Your answer
count = 10

def show_count():

show_count()

Press Ctrl⌘Enter to check your answer

Challenge 5

Complete add_bonus() by creating its own local total before updating it. Do not use global; the function should return 15.

python Your answer
def add_bonus():
    return total

print(add_bonus())

Press Ctrl⌘Enter to check your answer