Python Recursive Functions

Table of Contents

What is recursive function ?

Recursive function is a function that calls itself in order to create a loop.

 

Example of recursive function

def sum(number):
    if number == 0:
        return 0
    return number + sum(number - 1) # calls itself , which loops

print(sum(5))
15


In the above sum() is a recursive function which calls it self.
When we call the function sum with an integer 5, it recursively calls itself return number + sum(number - 1) , by decreasing number passed to it by1
There is a condition if number == 0, which checks the number values each time it is called and returns 0 once it reaches 0.
This condition has to be kept to avoid the number to become negative and to avoid the recursion to go to an infinite loop.
So the recursion function should have an condition to terminate recursion and avoid infinite loop 

The above recursion function purpose can also be solved using python loops. Loops are faster than recursion

sum = 0
for i in range(5+1): # range(5+1) -> [0, 1, 2, 3, 4, 5]
    sum += i
print(sum)
15

 

Advantages of recursive function

  • Recursive functions make the code looks clean reducing the code size
  • Recursive functions are extremely useful when applying the same solution
  • Recursive functions reduce unnecessary calling of function.

Disadvantages of recursive function

  • Recursive functions are not easy to debug
  • Recursive functions takes more memory
  • Recursive functions uses more processor time.
Click any Link
to navigate to certain page easily
Write a line to us
Your Email
Title
Description