Back to questions
JuniorTheoryCommon
What does the program print?
def evens(limit):
for n in range(0, limit, 2):
yield n
g = evens(7)
print(sum(g), sum(g))12 0
- Expecting
12 12, as ifgstarted over like a list: a generator gives its values once, and the firstsumtook them all, so the second sees none. - Expecting an error or
Nonefrom the secondsum: an exhausted generator acts as an empty iterable, and the sum of nothing is0.
- How would you change the last line so that it prints
12 12? - Why does
evens(7)not run the loop untilsumasks for values?