Iterators and generators
Project: stream study durations
Filter valid durations and compute a total lazily.
Lesson 58 of 63
Reading: about 1 min
Lesson + practice: about 19 min
Difficulty: Intermediate
On this page5 sections
Create a generator that reads lines, skips blanks, and yields positive integer durations. Let invalid nonblank lines raise a clear error.
Worked example
def durations(lines):
for line in lines:
text = line.strip()
if not text:
continue
value = int(text)
if value <= 0:
raise ValueError("minutes must be positive")
yield value
source = ["20\n", "\n", "25\n"]
print(sum(durations(source)))45
Why this works
The generator produces each validated number when sum requests it. Blank lines are skipped; int raises ValueError for nonnumeric text.
Another case
A generator does no work until a value is requested. The print calls show when each step runs.
def noisy(values):
for value in values:
print("reading", value)
yield value
generator = noisy([20, 25])
print("created")
print(next(generator))created reading 20 20
Practice
Try ["20", "bad"] and ["0"]. What happens?
Check the practice result
Reveal answer
Both raise ValueError: int rejects bad and the explicit rule rejects zero.
Try another case
What does sum(durations(["\n", " "])) return?
Check your answer
Reveal answer
0. Both lines are blank and skipped, so the generator yields nothing and the sum is 0.
Your progress
Reveal the check answer or reach the end to complete this lesson.