Python Generators
You have three station names, and you want them one at a time. The first line on the screen will be north. The next line will be east. The last line will be south.
def stations():
yield "north"
yield "east"
yield "south"
route = stations()
print(next(route))
print(next(route))
print(next(route))
The screen shows three lines. The first print writes north and nothing else. yield "north" is the line that hands that name back. The function does not go on to east until the next print asks. The second print writes east. The third print writes south. One print does not write all three names. The program is done. There is no fourth line.
📊 What each print writes
| Which print | The line on the screen |
|---|---|
| the first print(next(route)) | north |
| the second print(next(route)) | east |
| the third print(next(route)) | south |
After south, there is no yield left in stations. A fourth print(next(route)) is not in this program. Add that line and it stops as StopIteration, because there is no next name. None is not written. The screen you have stays north, then east, then south.
You can now ask for one station name, then the next, then the last. The screen is north, then east, then south. The next page puts a wrapper around a function.
One name, then the next
The first line is north. The second line is east. The third line is south. Each print asks once. The next page puts a wrapper around a function.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top