Recursion Function

What is Recursion ?

Recursion is the process of defining something in terms of itself.
Eg: Two mirrors faced each other parallel. Any object in between them would be reflected recursively.

Python Recursive Function

We know that in Python, a function can call other functions. It is even possible for the function to call itself. These type of functions are called as recursive functions.

Flow Chart

Example:

#Program to print factorial of a number using Recurion

def factorial(num):
    """
    This is a recursive function to find the factorial of a given number
    """
    return 1 if num == 1 else (num * factorial(num-1))

# Getting the input from user during run time
# Be default all the values will be changed to string
num = input("Enter valid integer number: ")  


# Converting String to integer value
num = int(num)
print("The number entered is ", num)

print("Factorial of {0} is {1} ".format(num, factorial(num)))

Output:
Enter valid integer number: 5
The number entered is  5
Factorial of 5 is 120 

Advantages

  1. Recursive functions make the code look clean and elegant.
  2. A complex task can be broken down into simpler sub-problems using recursion.
  3. Sequence generation is easier with recursion than using some nested iteration.

Disadvantages

  1. Sometimes the logic behind recursion is hard to follow through.
  2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
  3. Recursive functions are hard to debug.
Total Website Visits: 40427
© Copyright 2018 - 2020. All Rights Reserved.

Developed by Vinoth Rathinam

Leave a Reply