Python Recursion


In this section recursive functions will be discussed. A recursive function is that which calls itself. Recursion can be defined as to define something by itself.

 

Python Recursive Function

In Python we can call a function from another function. A function can be called by itself and this type of function will be called recursive function. Consider the following example in which a function is defined that will calculate the factorial of a number entered by the user and the function will be called by itself:

CODE

>>> def factorial(n):

          if n==1:

                   return 1

          else:

                   return(n*factorial(n-1))

>>> x = 5

>>> factorial(x)

OUTPUT

120

120

Factorial is defined as the product of all numbers or integers from 1 to the number whose factorial is to be calculated. In the above example a function is defined and in the definition of the function a condition is checked that if the number is 1 then return 1 because the factorial of 1 is 1 as 1 * 1 = 1. In the else part again the function is called, this time the value that is passed to the function will be 1 less than the value entered by user.

The function is called by decreasing the number entered by user. The function will be called until the number becomes 1 and the if condition stops the else part to be executed. This is called base condition and if the base condition is not specified then an infinite the recursion will be called an infinite number of times.

Then obtained number will be multiplied by the actual number entered by user and in this way the factorial will be calculated using the recursive function.

 

Advantages of Recursion

  1. A recursive function makes the code readable and easy to understand.
  2. Recursive functions modify a complex function into a simpler one.
  3. Recursive functions can be used instead of nested loops that become difficult to handle.

 

Disadvantages of Recursion

  1. It becomes hard for the user to understand the logic of recursive functions.
  2. Recursive functions take a lot of memory and a lot of time for execution.
  3. It becomes hard to debug recursive functions.