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 yield
1def countdown(n):
# Loop while n is positive
2 while n > 0:
# yield pauses the function and returns n
# The next call to next() resumes right after this line
3 yield n
# Decrease n after yielding
4 n -= 1
5
# for loop automatically calls next() on the generator
6for num in countdown(3):
# Print each yielded value
7 print(num)

Output

3
2
1
Practice typing this code

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

More Python examples at level 4

← Python typing practice