Python Fibonacci Series Using Recursive Function and Loop

In Python Fibonacci Series, next range uses the total of the previous two numbers. For example: 0, 1, 1, 2, 3, 5 , 8, 13, 21, 34, 55 and so on. Fibonacci series starts from 0 and 1.

Python Fibonacci Series

Fibonacci application is used in the Stock Market, Trading, Banking Application, Data structure, Graphs and much more.

The sequence Fn of Fibonacci numbers is defined by the recurrence relation:
Fn = Fn-1 + Fn-2

There are two ways to write the Fibonacci Series program in Python:

  1. Fibonacci Series using Loop
  2. Fibonacci Series using recursion

Fibonacci Series using Loop

In Loop, we are using while loop and counter for generating Fibonacci Series. In while loop, we are adding two numbers and swapping numbers.

nNum = 10
num = 0
num1 = 0
num2 = 1
count = 0

while (count<nNum):
    print(num1)
    num = num1 +num2
    num1 = num2
    num2 = num
    count +=1

Fibonacci Series using Recursion (Recursive Function)

In Recursive Function, we are using formula Fn = Fn-1 + Fn-2. We are also iterating using for loop. In each iterate, we are calling function recur_fibo().

# Recurrence Relation
# Fn = Fn-1 + Fn-2
def recur_fibo(n):
    if n <= 1:
        return n
    else:
        return(recur_fibo(n-1)+recur_fibo(n-2))

nNum = 10
for i in range(nNum):
    print(recur_fibo(i))
Share