×

Python Recursion

Recursion is one of the most interesting yet important concepts of any programming language. If you want to be a good programmer or data scientist, then you should better have a very good and deep understanding of recursion. Recursion functions are used everywhere in programming, from searching and sorting to other important concepts. Even in every interview, you can expect a question from recursion.

In this tutorial, we will understand recursion and how to implement it using Python. We will also understand it with an example to make it clearer.

What is Recursion?

Recursion can be understood as a concept in which a function calls itself. We are already familiar with the condition, where a function calls another function but in recursion, a function calls itself directly or indirectly. The function which implements recursion is known as a recursive function.

It’s very important to be very careful while writing a recursive code because if not written correctly, it can be very hard to debug it and it can also go in an infinite loop, which is not good for any program. But writing the code correctly and efficiently can be very useful.

Each recursive function has two features:

  1. Base case: It is the desired condition which should be reached for the recursive function to stop. This is the ultimate goal to achieve in a recursive function. It is mandatory to have a base case in a recursive function. Otherwise, the function would not be able to know when to stop and come out of the function. Hence can go into an infinite loop. Without a base case, the default depth for recursion is 1000. After that the compiler will show RecursionError.
  2. Recursive case: It is the case where the recursive functions keep going into another recursive function until they reach the base case. It is the middle stage of a recursive function.

Syntax

 def recursive_fun ( ):
          #recursive function calls
          recursive_fun ( )
recursive_fun( )

One thing to understand is that any problem that can be solved using a recursive function can also be solved using an iterative function with the help of a loop. But there are times when we should use loops and there are times when we should use a recursive function. Recursion divides a bigger problem into smaller functional problems and then solves them.

Let’s understand with an example.

Example1: Finding the factorial of a number.

Factorial of n = n * (n-1) * (n-2) * (n-3) *…..* 3 * 2 * 1

Iterative method

Code

def fact(n): 
    x = 1     
    for i in range(2, n+1):
        x *= i
    return x
 
num = fact(5);
print(num)

Output:

120

Explanation

In the above code, we have used the iterative approach to solve the problem. We have called the function named fact () once and inside that function we have used a loop for calculating the factorial. Once the loop reaches the boundary condition, we come out of the loop and return the factorial value. The factorial value will be stored in the variable named num and then we will print it.

Recursive method

Code

def fact(n):
    # Base Case
    if n==0:
        return 1
    # Recursive Case
    return n*fact(n-1)


fact_num = fact(5)
print(fact_num)

Output:

120

Explanation

In the above code, we have used the recursive approach to solve the problem. We have called the function named fact with a value of 5. In this function, we have written our base case (if n is equal to zero, then return one) and the recursive case. If the argument satisfies the base condition, we will come out of the recursive function (go to the recursive function with an argument as n-1). Otherwise, we will enter into another recursive function with a different argument. This process will continue until we reach the base case.

What are Direct and Indirect Recursion?

Direct recursion is the default recursion method where a function invokes itself. Indirect recursion is when a function calls another function and then eventually gets invoked. Let’s say function A calls Function A then it is a direct recursion while if function A calls function B and function B calls function C and function C calls function A then it is indirect recursion because eventually function A gets called recursively.

Syntax:

Direct Recursion

def fun ( ):
    #recursive call
     fun ( )


#function call
fun( )

Indirect Recursion

def funA( ):
     #calls another function
     funB( )


def funB( ):
     #calls another function
     funC( )


def funC( ):
      #calls again the first function
      funA( )


funA( )

Advantage of Recursion

  • Recursion helps in making the code more clean and readable.
  • In recursion, we can divide a bigger problem into smaller ones and then solve them efficiently.
  • It is easier to generate sequences using recursion than using nested iteration.

Disadvantage of Recursion

  • In recursion, a lot of time and memory are needed which makes it an expensive function.
  • It can easily get out of hand with just simple coding mistakes. Hence it’s very peculiar.
  • It is hard to debug a recursive code.
  • Sometimes it can be hard to understand a recursive function's logic.

Related Topics

Python vars() Function

Python vars() Function The vars() function in Python returns the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute. Syntax vars([object]) Parameter object: This parameter represents any object with a __dict__attribute Return This function returns...

1 minute read.

Data Class in Python

Introduction In Python 3.7, the dataclass modules are introduced as a practical tool for creating organized classes designed specifically for data storage. These classes contain specific attributes and capabilities to deal...

6 minutes read.

Python String isalnum() method

Python String isalnum() method The string.isalnum () method in Python returns a boolean value true if all characters in the string are alphanumeric else for any other value it returns false. Syntax String.isalnum() Parameter NA Return This...

1 minute read.

Python program to perform the arithmetic operation

Python program to perform the arithmetic operation This program will write a code to perform some basic arithmetic operations like addition, subtraction, multiplication, exponent, modulus, and division. Here we first need...

2 minutes read.

Python List append() Method

Python List append() Method The list.append() method in Python adds or appends an item to the end of the list. Syntax list.append(x) Parameter x: It is a required parameter that represents an element of any type (string, number,...

1 minute read.

How to Concat two Dataframes in Python

Using Pandas dataframe, we can concat two dataframes or series in Python. So let's take a brief introduction to what is Pandas in Python. Pandas is a library typically used for...

7 minutes read.

Speech Recognition in Python

What is Speech Recognition? Speech Recognition is a term defined for automatic recognition of human speech. Speech recognition is the most significant activity in the domain of the interaction between the...

8 minutes read.

Binary Search Visualization using Pygame in Python

A calculation like Binary Search is seen effectively by picturing. Here in this tutorial, a function that pictures the Binary Search Algorithm is carried out. The Graphical User’s Interface (GUI)...

15 minutes read.

Python Program to Check Leap Year

Python Program to Check Leap Year Leap year: We all know that each year has 365 or 366 days. But whenever a year has 366 days, then the year is said...

2 minutes read.

Sort a dataframe based on a column in Python

Sorting the dataframe based on a column requires pandas which is An open-source library called Python Pandas is described as offering high-performance data processing in Python. For both professionals and...

4 minutes read.

Python Logging Maxbytes

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

6 minutes read.

Python program for perfect number

Python program for perfect number Before writing any program for a given problem, we have to understand the problem for which we are creating a solution program. So, let's understand what...

2 minutes read.

Creating Web Application in python

Web Application :  Web Application is an application software that runs in web browser . Software programs will run on operating system. Whereas Web Applications will run on World Wide Web...

5 minutes read.

API Requests using Python

What is an API? API stands for Application Programming Interface. It is commonly known as API. It provides an environment that helps two or more computer programs to contact each other....

5 minutes read.

The Calendar Module of Python

The calendar module provides calendar features, including printing functions for a specific month or year. Default is the first day of the week on Monday and the last day on Sunday...

3 minutes read.

Python Percentage Sign

In Python, the percentage sign significantly completes two things. They are: It goes about as a Modulo administrator. It helps in string organizing. Allow us to see every one of them plainly. Modulo operator: Like...

2 minutes read.

What is the Python Global Interpreter Lock?

Introduction When working with processes, Python employs a form of process lock called the Global Interpreter Lock (GIL). Python typically executes a collection of typed statements using just one thread. It...

4 minutes read.

Add in Dictionary Python

Dictionary in python: Dictionaries are a useful data configuration for storing information in Python because they can mimic real-world data arrangements where a particular value exists for a particular key. The...

4 minutes read.

How to check data type in python

The data type represents the nature of a variable; it determines what kind of data it can store and what operations can be carried out on it. There are five...

4 minutes read.

wxPython Panel class

wxPython Panel class The Widgets which is shown in the frame of GUI window such as text box, buttons, static text etc. are put inside the panel class of the wxpython...

2 minutes read.