Generator Function in Python
Level 482 keystrokes
This creates a generator that yields values one at a time, printing 3, 2, 1. Generators are memory-efficient iterators.
Python code
# Define a generator function using yield1def countdown(n): # Loop while n is positive2 while n > 0: # yield pauses the function and returns n # The next call to next() resumes right after this line3 yield n # Decrease n after yielding4 n -= 15 # for loop automatically calls next() on the generator6for num in countdown(3): # Print each yielded value7 print(num)Output
3 2 1
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
:× 3(× 3)× 3-× 1=× 1>× 1