Exercises
Closures
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Write multiplier so triple(5) gives 15.
Python
# define multiplier
triple = multiplier(3)
print(triple(5))Define a function inside and return it; it remembers factor.
def multiplier(factor):
def multiply(n):
return n * factor
return multiply
triple = multiplier(3)
print(triple(5))Exercise 2Passed
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())The name lives in the enclosing function, not the module.
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
counter = make_counter()
print(counter(), counter())Exercise 3Passed
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])A default argument is evaluated at definition time.
funcs = []
for i in range(3):
funcs.append(lambda i=i: i)
print([f() for f in funcs])