Numbers · beginner
Python Program to Print the Fibonacci Sequence
Print the Fibonacci sequence in Python with a loop and tuple unpacking, and see why the naive recursive version gets so slow, plus a cached fix.
- while and for loops
- tuple unpacking
- recursion
- functools.cache
In the Fibonacci sequence each number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13, … It appears in nature (spirals in sunflowers and pine cones) and is the standard example for comparing loops with recursion.
The program
n = 10
a, b = 0, 1
terms = []
for _ in range(n):
terms.append(a)
a, b = b, a + b
print(f"First {n} Fibonacci numbers:")
print(*terms, sep=", ")First 10 Fibonacci numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34How it works
- a and b hold two consecutive Fibonacci numbers, starting with 0 and 1.
- Each pass appends a, then moves both one step forward: the new a is the old b, and the new b is the sum of the old pair.
- a, b = b, a + b computes the right side first, so no temporary variable is needed (see swapping two variables).
- print(*terms, sep=", ") unpacks the list into separate arguments and prints them separated by commas.
Watch it run line by line
Watch a and b move forward together on the a, b = b, a + b line while the terms list grows by one item per loop. It is the clearest way to see why tuple unpacking matters here.
“Visualize step by step” opens the program in the Python Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: Recursive, with a cache
The recursive definition fib(n) = fib(n - 1) + fib(n - 2) recalculates the same values again and again: fib(30) makes over a million calls. @cache remembers each result, so every value is calculated only once.
from functools import cache
@cache
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print([fib(i) for i in range(10)])
print(fib(80))[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
23416728348467685Common mistakes
- Updating a and b on two separate lines (a = b, then b = a + b): by the second line a has already changed, so the sequence goes wrong.
- Using plain recursion for large n: fib(40) without a cache takes many seconds.
- Mixing up conventions: some sources start the sequence at 1, 1. Say which one you use.
Try it yourself
- Print all Fibonacci numbers below 1,000 with a while loop.
- Write a generator function that yields Fibonacci numbers forever, and take the first 15 with itertools.islice.
- Check that the ratio of consecutive terms approaches the golden ratio, about 1.618.
Open the program in the Python Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 Python examples, or write your own program in the online Python Compiler.