Exercises
Generators
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Write countdown as a generator that yields 3, 2, 1.
Python
# define countdown
print(list(countdown(3)))yield inside a while loop.
def countdown(n):
while n > 0:
yield n
n -= 1
print(list(countdown(3)))Exercise 2Passed
Sum the squares below 1000 without ever building a list.
Python
# print the total
A generator expression inside sum() needs no extra brackets.
print(sum(n * n for n in range(1000)))Exercise 3Passed
The second sum gives 0. Fix it so both print the same total.
Python
squares = (n * n for n in range(4))
print(sum(squares))
print(sum(squares))A generator is used up after one pass. Keep the values.
squares = [n * n for n in range(4)]
print(sum(squares))
print(sum(squares))