Python – Recursion and Recursive Function

After reading this Python Recursion and Recursive Function topic, you will able to use Recursion in Python, you will understand the theory and example also you will know the Advantages and Disadvantages.

The function call itself is known as recursive function and the recursion is the process where the function called itself. The recursive function also referred as self-called function. Whenever function called from itself then there will be an infinite loop. To break this infinite loop every recursive function must check the terminating condition and then decide whether to call function again or not.

Example:

Program (1): To demonstrate how to use the recursive function for calculating factorial of a number in Python.

def factorial(n):
#logic to find factorial of a number  
   if n == 0:
       return 1
   else:
       return (n * factorial(n - 1))
print(" 6! = ", factorial(6))

Output (1)

6! = 720

Explanation:

In the example above is to calculate factorial of number based on recursive function as factorial(n). When terminating condition if n == 0: examined to the true condition, the recursive function return factorial of a number.

Recursion Advantages

  • Recursive function requires less coding.
  • In Recursion, we break down a complex problem into smaller ones whose answer we already know.

Recursion Disadvantages

  • Recursive function logic is sometimes difficult to construct.
  • If proper coding is not done, then the recursive function may lead to an infinite loop.
  • During recursive function calls, recursion requires more time and memory because of the indirect computation of time and memory.

Published by

Electrical Workbook

We provide tutoring in Electrical Engineering.

Leave a Reply

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