×

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 List

The list is one of the most versatile, mutable data-structures in Python. It can store heterogeneous data or different types of data. The list contains comma-separated values (item) within the square brackets. Creating...

4 minutes read.

Python Sending Email

Python Sending Email Simple Mail Transfer Protocol (SMTP) is used to handle sending e-mail and routing e-mail between mail servers. When we send an email either form a web-application or from a local software...

3 minutes read.

Assignment Operators in Python

The prime usage of Assignment Operators is to assign values to variables. These are taken into account to do operations on values and variables. There are some special symbols in python...

4 minutes read.

Python SciPy Library

Introduction SciPy, a logical library for Python is an open-source, BSD-authorized library for arithmetic, science, and design. The SciPy library relies upon NumPy, which gives advantageous and quick N-dimensional exhibit control....

6 minutes read.

How to Open a File in Python with a Path?

File in Python File handling is an important operation; it allows the programmer to access the data in the files, such as text, binary values and excel sheets. The CSV files...

7 minutes read.

Python ord() Function

Python ord() Function The ord() function in Python returns the number representing the Unicode code of a specified character. Syntax ord(c) Parameter c: This parameter represents a string or any character. Return This function returns the number...

1 minute read.

Data Structures and Algorithms using Python | Part 2

Files: A file is a location or information stored in computer storage devices. File handling is essential when the information or the data is to be held permanently. When we try to...

20 minutes read.

How to learn python Online

Need to Learn a Programming Language 1. To get a high Paying job We know that Software Engineering is one of the top-paying professions in the world. The top criteria to be...

3 minutes read.

Python Project Ideas Based On Django

Introduction If you have learned Python and you are an expert in Django, then your practical skills should be excellent in this field. If you want to check your practical skills,...

9 minutes read.

Scrimba python

Scrimba allows you to study whenever and wherever the topics or concepts you want. It also replaces classroom instruction with interactive screencasts, live events, and student-to-student help. Scrimba is an interactive...

3 minutes read.

Python max() function

Python max() function The max() function in Python returns the largest item in an iterable or the largest of two or more arguments. Syntax max(iterable, *[, key, default])               or max(arg1, arg2, *args[, key])   Parameter arg1, arg2, *args: This...

1 minute read.

Python String startswith() method

Python String startswith() method The string.startswith() method in Python returns a boolean value ‘True’ if the given string starts with the prefix, otherwise it returns False. Syntax startswith(prefix[, start[, end]]) Parameter prefix: This parameter signifies the value to check. start(optional):...

1 minute read.

Python Dictionary fromkeys() method

Python Dictionary fromkeys() method The dictionary.fromkeys() method in Python creates a new dictionary from the given sequence of elements and returns a dictionary with the specified keys and values. Syntax dictionary.fromkeys(sequence[, value]) Parameter sequence- This...

1 minute read.

Periodogram in Python

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python String rsplit() method

Python String rsplit() method The string.rsplit() method in Python splits a string into a list, starting from the right. If the "max" parameter is not specified, this method will return the...

1 minute read.

Io stringio Python

Python programming language: 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...

7 minutes read.

ER diagram of the Bank Management System in python

What is an ER diagram? The full form of the ER diagram is the Entity Relationship diagram. This diagram is used in database management systems to have a rough idea of...

3 minutes read.

Find Last Occurrence of Substring using Python

Introduction When planning to work with strings, we may need to determine whether a substring is present. This issue is rather typical, and there have been numerous discussions about how to...

3 minutes read.

Python TCP Server

The TCP server library is also known as the socket library. Socket programming is the method of connecting two nodes through a network to form communication between two nodes. In...

3 minutes read.

Working with CSV files in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

7 minutes read.