← Previous Module 11: Iterators & Generators Next →
Statement
Solution

Python Exercise 11.2: Fibonacci Generator

The Fibonacci sequence is a classic programming challenge. In this exercise, you will write an infinite generator that yields Fibonacci numbers one at a time — and then use it to print the first 20 numbers in the sequence.

Your generator function fibonacci() should:

  • Require no parameters.
  • Start the sequence with 0 and 1.
  • Use a while True loop to yield values indefinitely.
  • After each yield, update the two tracking variables to advance the sequence: the new pair should be (b, a + b).

After defining the generator:

  • Create a generator object by calling fibonacci().
  • Use a for loop with range(20) to print the first 20 Fibonacci numbers, one per line, using next().

Sample Output (first 20 Fibonacci numbers):

Input
Output
(no input required)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

Solution

The generator uses simultaneous assignment (a, b = b, a + b) to advance the sequence each iteration without needing a temporary variable.

def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b gen = fibonacci() for _ in range(20): print(next(gen))

Key Concepts:

  • An infinite generator uses while True with yield — it never raises StopIteration on its own, so the caller must control how many values to consume.
  • yield a pauses execution and returns the current value; the generator resumes from exactly this point on the next next() call.
  • Simultaneous assignment a, b = b, a + b evaluates the right side fully before assigning, so no temporary variable is needed.
  • next(gen) manually advances the generator and retrieves the next yielded value.
  • Using for _ in range(20) is idiomatic when the loop variable itself is not needed inside the loop body.
Python 3
Test Console
Run code to see output...

Go Beyond Learning. Get Job-Ready.

Build in-demand skills for today's jobs with free expert-led courses and practical AI tools.

Explore All Courses
Scroll to Top