Editor

Infinite Fibonacci Generator

Advanced · Write the code · from Python Generators: Process Millions of Items Without Running Out of Memory

From the lesson: Can You Communicate with a Running Generator?

Generators aren't just one-way streets. You can send values back into a paused generator, throw exceptions into it, or close it early.

Read this part of the lesson

Write a generator function fibonacci() that yields an infinite sequence of Fibonacci numbers starting with 0, 1, 1, 2, 3, 5, 8, ...

Then use it to print the first 10 Fibonacci numbers.

def fibonacci():
# Yield infinite Fibonacci numbers
pass
# Print the first 10 Fibonacci numbers
count = 0
for fib in fibonacci():
print(fib)
count += 1
if count == 10:
break

More Generator exercises

All Python exercises · 50 practice problems · Advanced Python quiz