Chapters
Python114 chapters

Exercises

Closures

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

Exercise 1

Write multiplier so triple(5) gives 15.

Python
# define multiplier

triple = multiplier(3)
print(triple(5))
Exercise 2

The counter does not increment. Make it remember its own count.

Python
def make_counter():
    count = 0

    def increment():
        count += 1
        return count

    return increment

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

All three functions return 2. Make them return 0, 1 and 2.

Python
funcs = []
for i in range(3):
    funcs.append(lambda: i)

print([f() for f in funcs])