Editor

Python Program to Print the Fibonacci Series

Beginner · Numbers · CBSE class 11 practical list · CBSE class 12 practical list

The Fibonacci series starts with 0 and 1, and each next term is the sum of the two terms before it: 0, 1, 1, 2, 3, 5, 8, 13 and so on. This program prints the first n terms of the series.

Program

fibonacci_series.py
n = 10 # or: n = int(input("How many terms? "))
a = 0 # first term
b = 1 # second term
print("First", n, "terms of the Fibonacci series:")
for i in range(n):
print(a, end=" ")
next_term = a + b
a = b
b = next_term
print()
Output
First 10 terms of the Fibonacci series:
0 1 1 2 3 5 8 13 21 34

How it works

  1. a and b hold the two most recent terms, starting at 0 and 1.
  2. Each pass of the loop prints a, then works out the next term as a + b.
  3. The terms then move along by one: a takes the value of b, and b takes the new term.
  4. end=" " prints the terms on one line, and the final print() ends that line.

Other ways to write it

Using recursion

Using recursion
def fibonacci(k):
# Term k is the sum of terms k - 1 and k - 2
if k <= 1:
return k
return fibonacci(k - 1) + fibonacci(k - 2)
series = []
for i in range(10):
series.append(fibonacci(i))
print("Fibonacci series:", series)
Output
Fibonacci series: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

A recursive function matches the definition closely, but it repeats a lot of work and gets slow beyond about 30 terms.

Terms up to a limit

Terms up to a limit
limit = 100
a, b = 0, 1
series = []
while a <= limit:
series.append(a)
a, b = b, a + b
print(f"Fibonacci numbers up to {limit}: {series}")
Output
Fibonacci numbers up to 100: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

A while loop suits a limit on the value rather than a count of terms, and a, b = b, a + b updates both terms at once.

Try it yourself

Change the program to print only the even terms among the first 20.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises