Python programs / Numbers / Fibonacci sequence

Python Program to Print the Fibonacci Sequence

Beginner Numbers

Builds the first n terms of the Fibonacci sequence, where each term is the sum of the two before it, as a list.

In the Fibonacci sequence, each term is the sum of the two before it, starting from 0 and 1: 0, 1, 1, 2, 3, 5, 8, 13 and so on (5 + 8 = 13). It's a favourite school program because the loop has to remember the last two terms as it goes.

Program

def fibonacci(n):
    """The first n terms of the Fibonacci sequence, as a list."""
    terms = []
    a, b = 0, 1
    for _ in range(n):
        terms.append(a)
        a, b = b, a + b
    return terms


print("First 10 terms:", fibonacci(10))
print("First 1 term:", fibonacci(1))

Open in the editor Download fibonacci.py

Output

First 10 terms: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
First 1 term: [0]

How it works

  1. terms is the list the function fills and returns.
  2. a and b hold the next two terms to come. They start as 0 and 1, the first two terms.
  3. The loop runs n times and adds a to the list each time. _ is the usual name for a loop variable that isn't used.
  4. Both move one step along the sequence: a becomes b, and b becomes the term after it, a + b. Python works out the right-hand side before it assigns anything, so a + b uses the old a.
  5. The finished list goes back to the caller.
  6. The program prints the first 10 terms, then the first 1, which is only 0.

The first five rounds of the loop:

Round Added to the list a, b after line 7
1 0 1, 1
2 1 1, 2
3 1 2, 3
4 2 3, 5
5 3 5, 8

Other ways to write it

From the list itself

Each new term can come from the list: terms[-1] and terms[-2] are its last two items. terms[:n] at the end keeps the answer right when n is 0 or 1.

def fibonacci(n):
    terms = [0, 1]
    while len(terms) < n:
        terms.append(terms[-1] + terms[-2])
    return terms[:n]

print(fibonacci(8))

With recursion

Some exams ask for a function that returns the nth term by calling itself for the two terms before it (recursion). It's short but slow, as it works out the same terms again and again: fib(30) makes over 2.6 million calls.

def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

print([fib(i) for i in range(10)])

Try it yourself

  • Print the first 20 terms: the last one is 4181.
  • Start the sequence at 1 and 1 instead, as some books do.
  • Print only the terms below 100 with a while loop. There are 12, up to 89.
  • Add up the first 10 terms with sum(): the total is 88.

More numbers programs

Share this program