Search⌘ K
AI Features

Solution Review: Generator for Fibonacci Numbers

Explore how to implement a Fibonacci number generator function in Python using the yield statement. Understand how the generator maintains state and produces an infinite sequence of values efficiently, making it easy to iterate over Fibonacci numbers without excessive memory usage.

We'll cover the following...

Implementation

Python 3.8
def fibonacci():
c = 0
n = 1
while True:
yield c
c, n = n, c + n
for i in fibonacci():
print(i)
if i > 100:
break

Explanation

We implement our fibonacci generator by using a yield statement in the function.

We start by defining two local variables, c and n. They are initialized to the first two elements of the Fibonacci series, i.e., 0 and 1, respectively. c stores the current element in the sequence that should be ...