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
Step through the program line by line: each step below shows up as its line runs.
-
termsis the list the function fills and returns. -
aandbhold the next two terms to come. They start as 0 and 1, the first two terms. - The loop runs
ntimes and addsato the list each time._is the usual name for a loop variable that isn't used. - Both move one step along the sequence:
abecomesb, andbbecomes the term after it,a + b. Python works out the right-hand side before it assigns anything, soa + buses the olda. - The finished list goes back to the caller.
- 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
whileloop. There are 12, up to 89. - Add up the first 10 terms with
sum(): the total is 88.