Python Program to Display Fibonacci Sequence Using Recursive Function

In this example, we will write a program that displays a fibonacci sequence using a recursive function in Python. To better understand this example, make sure you have knowledge of the following tutorials:-

A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8…

The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms. This means to say the nth term is the sum of (n-1)th and (n-2)th term.

Python Program to Display Fibonacci Sequence Using Recursive Function

def fibo(n):
    if n <= 1:
        return n
    else:
        return fibo(n-1) + fibo(n-2)


terms = int(input("How many terms? "))

if terms  <= 0:
    print("Please enter a positive integer")
else:
    print("Fibonacci sequence:")
    for i in range(terms):
        print(fibo(i))

The output of the above program is:-

How many terms? 8
Fibonacci sequence:
0
1
1
2
3
5
8
13
Program Explanation:-
A function named fibo() is defined that takes an argument which calculates the sum of two previous values of the argument n. The base condition for the recursive function is n <= 1 as the recursive function calculates the sum from the nth term. The Fibonacci sequence is printed using for loop.
SHARE Python Program to Display Fibonacci Sequence Using Recursive Function

You may also like...

Leave a Reply

Your email address will not be published.

Share