Python recursive function

Functions can call another. However, functions can call themselves too, if a function calls itself, this is termed as recursion. Recursion is an important concept in programming as it helps to do a certain tasks in a clean and efficient manner. 

The most common example of recursion is calibration of factorial number, calibration of sum of positive natural numbers, and calibration of fibonacchi series. Lets look at these example below.

Example 1: Factorial Calculation using recursion

For any number n, factorial is calculated by using the formula below

n! = n* (n-1) * (n-2)*...* 3*2*1

Factorial function

def factorial(n):
    if n <= 1:
        return n
        return n * factorial(n - 1)

print("5! =", factorial(5))


5! = 120

The above factorial example calls the same function over and over again. If we allow this forever then it would result in an infinite loop, to resolve this issue in python we have maximum recursion depth. In short, we can call the same function upto a certain limit, if we exceed this limit then we get a maximum recursion depth exceeded error.

In above example if we use 999 instead of 5 then it will throw maximum recursion depth exceed error. We need to know that this way we can only calibrate factorial up to 998 number.

Example 2: Sum of N natural number

Let’s calibrate sum of n positive natural number.

def sum_of_positive_natural_numbers(n):
    if n <= 1:
        return 1
        return n + sum_of_positive_natural_numbers(n - 1)

print("Sum of 50 natural numbers", sum_of_positive_natural_numbers(50))


Sum of 50 natural numbers 1275

Example 3:  Fibonacci series generation

Let’s generate the sequence of fibonacchi using recursion. We know that the fibonacchi sequence is a sequence of numbers where the third element is the sum of the previous two elements.

term = 0
def fibonacchi_call_function(number_of_sequence):
    global term
    term = number_of_sequence
    prev_number = 0
    number = 1
    print("fibonacchi sequence of ", term, " is :")
    print(number, end='\t')
    fibo(prev_number, number)

i = 1

def fibo(prev_number, number):
    global i
    next_number = 0
    if i == term:
        return 0
        next_number = prev_number + number
        prev_number = number
        number = next_number
        print(next_number, end="\t")
        i += 1
        fibo(prev_number, number)
    return 0



fibonacchi sequence of  10  is :
1	1	2	3	5	8	13	21	34	55	

Leave a Reply

Your email address will not be published. Required fields are marked *