Home / Python / Example programs / Loops and numbers

Python program: Fibonacci sequence

Print the first terms of the Fibonacci sequence, where each number is the sum of the two before it.

The code

def fibonacci(count):
    a, b = 0, 1
    terms = []
    for _ in range(count):
        terms.append(a)
        a, b = b, a + b
    return terms

print(fibonacci(15))

Output

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]

How it works

Two variables hold the last two numbers. a, b = b, a + b moves them along in one step. _ is the usual name for a loop variable you do not use.

Python features used

Learn the ideas behind it in the free lesson Loops.