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
0and1. - Use a
while Trueloop 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
forloop withrange(20)to print the first 20 Fibonacci numbers, one per line, usingnext().
Sample Output (first 20 Fibonacci numbers):
Solution
The generator uses simultaneous assignment (a, b = b, a + b) to advance the sequence each iteration without needing a temporary variable.
Key Concepts:
- An infinite generator uses
while Truewithyield— it never raisesStopIterationon its own, so the caller must control how many values to consume. yield apauses execution and returns the current value; the generator resumes from exactly this point on the nextnext()call.- Simultaneous assignment
a, b = b, a + bevaluates 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.