Skip to main content

Fibonacci Series Program in Python

In our previous Python tutorial, you have learned how to Make Password Generator in Python. In this tutorial, we will explain about Fibonacci Series and write a Python program to create a Fibonacci Series.

A positive integer input needed to find the Fibonacci Series up to the Nth. The numbers of series are printed using Loops or Recursion until the Nth term given as an input.

What is Fibonacci Series

A Fibonacci sequence is a series of numbers where the next number is the sum of the two numbers just before it.

Fibonacci sequence:

0, 1, 1, 2, 3, 5, 8, 13
0 + 1 = 1
1 + 1 = 2
1 + 2 = 3
2 + 3 = 5
3 + 5 = 8
5 + 8 = 13

In above integer sequence of numbers, you can see the next number of sequence is always sum of the two numbers just before it. The first 0, 1 is default value.

In mathematical terms, the sequence Fn of Fibonacci numbers is always defined by the recurrence relation.

Fn = Fn-1 + Fn-2

with seed values

F0 = 0 and F1 = 1.

Fibonacci Sequence using Python

Here we will create Fibonacci Sequence using loop. We will take the positive number as input and loop through to form the series upto the integer input N as the range.

We will start loop from 2 to the Nth term as 0 and 1 are the seed values for forming the series.

Let’s implement the logic using Python. We will define a function fibonacci(n) that take number as parameter. We will implement logic to loop through input number to get series to Nth term. Then we will call function and pass positive integer number to get series.

Here is complete code to get Fibonacci Sequence using Python.

def fibonacci(n):

    if n < 0:
        print("Enter a positive number")
    else:
        print("Fibonacci sequence:")
        firstNum = 0
        secondNum = 1

        print(firstNum)
        print(secondNum)

        for i in range(2, n):
            sum = firstNum + secondNum
            firstNum = secondNum
            secondNum = sum
            print(sum)
			
fibonacci(10)

Output:

Fibonacci sequence:
0 
1 
1 
2 
3 
5 
8 
13
21
34