Python Recursive Functions

A recursive function is one which calls itself. Recursive functions provide some fruitful advantages over normal functions that we will be discussing on this tutorial. Make sure you have followed through following tutorials before proceeding the recursion:-

Loading…

Let us understand the recursive function using an example of factorial. Here a factorial is calculated as 5! = 5*4*3*2*1 = 120. The recursive function needs some kind of pattern to make it callable to itself.

def factorial(x):
    if x == 1:
        return 1
    else:
        return x * factorial(x-1)

num = 5
print("The factorial of", num, "is", factorial(num))

Its output is:-

The factorial of 5 is 120

How recursive functions work in Python?

Here we defined a function factorial() which takes an argument x. Note that recursive function should have a base condition which will stop the infinite loop that recursion causes. Here, if x == 1, we are stopping the recursion. Inside the function, the call is again made to factorial function but with the value decremented by 1. The recursive execution of the above program is as below:-
factorial(5) # 1st call with 5
5 * factorial(4) # 2nd call with 4
5 * 4 * 3 * factorial(3) # 3rd call with 3
5 * 4 * 3 * 2 * factorial(2) # 4th call with 2
5 * 4 * 3 * 2 * 1 * factorial(1) # 5th call with 1
5 * 4 * 3 * 2 * 1 # return from the 5th call as num=1
5 * 4 * 3 * 2 # return from the 4th call
5 * 4 * 6 # return from the 3rd call
5 * 24 # return from the 2nd call
120 # 1st call with 5 # return from the 1st call

What are the Advantages of Recursive functions in Python?

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

What are the disadvantages of Recursive functions in Python?

  • Sometimes the logic behind recursion is hard to follow through.
  • Recursive calls are inefficient as they take up a lot of memory and time.
  • Recursive functions are hard to debug.
Loading…