Ad Code

How to Write Python Recursive Function


Recursive function


Recursive functions act like loops that they iterate within the function to perform some operation. 

Since you are calling the same function in the function definition, it's called recursive. The developer must follow some rules to write a recursive function. 

Else, it will go into a loop. So developers must check twice the recursive function code.

Four rules

Here are the four top rules you need to consider, before you write a recursive function.
  • There must be a key variable, which will be responsible for the termination of recursion.
  • To determine the base value, which the key variable has to meet to reach the termination.
  • To make sure the key variable must approach the base value in every recursive call.
  • To make the recursive function terminate when the key variable reaches the base value.


Python recursive function

Here is a sample 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)


Advantages  

Here are top 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

Disadvantages

These are disadvantages of a recursive function.
  • It's hard to develop
  • Its is hard to understand the recursive functions

Post a Comment

0 Comments