Editor

Fix the Generator Bug

Advanced · Fix the bug · from Python Generators: Process Millions of Items Without Running Out of Memory

From the lesson: Can You Communicate with a Running Generator?

Generators aren't just one-way streets. You can send values back into a paused generator, throw exceptions into it, or close it early.

Read this part of the lesson

This generator should count words, yielding the running count after each word is sent. But it has a bug. Fix it.

def word_counter():
    count = 0
    while True:
        word = yield
        count += 1
        print(f'Word {count}: {word}')

Expected output when used:

Word 1: hello
Word 2: world
Word 3: python
def word_counter():
count = 0
while True:
word = yield
count += 1
print(f'Word {count}: {word}')
wc = word_counter()
# Something is missing here...
wc.send('hello')
wc.send('world')
wc.send('python')

More Generator exercises

All Python exercises · 50 practice problems · Advanced Python quiz