Python - Find the Fibonacci Sequence using Recursion

In this program, you will learn how to find the fibonacci sequence of any given number n using recursion.


Fibonacci sequence 0,1,1,2,3,5,8,....etc. It is a interger sequence.
The first two numbers are 0 and 1. You can get fibonaci sequence by adding the prededing numbers the two terms. Fibonacci sequence represents for nth term is sum of (n-1)th and (n-2)th term.
Example: 5 terms # - 0 # - 1 # - 0, 1, 0+1 # - 0, 1, 1, 1+1 # - 0, 1, 1, 2, 1+2 # - 0, 1, 1, 2, 3


Program Code



    # This program to display fibonacci sequence using recursion for given n-th term

    def fibonacci_rec(tnum):
    if tnum <= 1:
        return tnum
    else:
        return (fibonacci_rec(tnum -1) + fibonacci_rec (tnum -2))

    tnum = int(input('Enter how many terms you want to display: '))
    # check n-th term is valid
    if tnum <= 0: 
        print('Please enter a positive integer to display fibonacci sequence')

    else:
        print("Fibonacci Sequence is")
        for i in range(tnum):
            print(fibonacci_rec(i)) 
    

Output



    Enter how many terms you want to display: 10
    Fibonacci Sequence is
    0
    1
    1
    2
    3
    5
    8
    13
    21
    34

In this program, the number of terms stored in tnum variable which is 10. You can change the value of tnum to find the fibonacci sequence for different numbers.

The first term and second term values are stored as 0 and 1 respectively.

A recursive function fibonacci_rec is used to calculate the nth term of the sequence. We used for loop to iterate and caluculate each term recursively.

The following topics can be useful to understand this program.



Related Tutorials