How to Write Python Recursive Function

Recursion in Python

RECURSIVE function python acts like a loop that iterate within the function to perform some operation.

Precisely, if you call the same function from function is called recursive function. There are rules the developer must follow to write a recursive function. The incorrectly written function goes into infinite loop.

4 Rules to write recursive function in Python

Below, you will find the four rules you need:

  1. There must be a key variable, which will be responsible for the termination of recursion.
  2. To determine the base value, which the key variable has to meet to reach the termination.
  3. To make sure the key variable must approach the base value in every recursive call.
  4. To make the recursive function terminate when the key variable reaches the base value.

Python recursive function example

Here is an example python recursive function.

# This program computes the factorial of a number using recursion
#function definition
def fact(n):
"computes factorial using recursion"
if n == 0:
    return 1
else :
    return n * fact(n - 1)

# Function call
num = input("enter a number:")
num = int(num)
result = fact(num)
print("factorial=", result)

Recursive function advantages  

There are two prime advantages of a recursive function.
  • Recursive functions divide the problem into smaller similar fragments and then computes them.
  • The recursive code looks precise and cleaner as compared to using loops. Here is how to call SQL from python

Recursive function disadvantages

Below, you will find the absolute disadvantages of recursive function.
  • It's hard to develop
  • Its is hard to understand the recursive functions

Post a Comment

Thanks for your message. We will get back you.

Previous Post Next Post