Skip to content
Devtoolry

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.

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

Python
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=", ")
Output
First 10 Fibonacci numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34

How it works

  1. a and b hold two consecutive Fibonacci numbers, starting with 0 and 1.
  2. 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.
  3. a, b = b, a + b computes the right side first, so no temporary variable is needed (see swapping two variables).
  4. 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.

Python
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))
Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
23416728348467685

Common 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.

Browse all 25 Python examples, or write your own program in the online Python Compiler.