Chapters
Python114 chapters

Exercises

Scope

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

bump should change the module-level count. Make it work.

Python
count = 0

def bump():
    count += 1

bump()
print(count)
Exercise 2

Make the counter remember its own count between calls.

Python
def make_counter():
    count = 0

    def increment():
        count += 1
        return count

    return increment

counter = make_counter()
print(counter(), counter(), counter())
Exercise 3

This shadows the builtin sum. Rename the local so the builtin stays available.

Python
def total(numbers):
    sum = 0
    for n in numbers:
        sum += n
    return sum

print(total([1, 2, 3]))
print(sum([1, 2, 3]))