×

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 bin() function

Python bin() function The bin() function in Python returns the binary version for the specified integer. Syntax bin(x) Parameter n: This parameter represents an integer or int value. Return This function returns a binary string for the specified integer...

1 minute read.

Python Classification

Identification and grouping of items or concepts into specified categories this process is known the classification. Data can be separated and sorted in data management according to predetermined criteria for...

6 minutes read.

Python property()

Python property() class The property() class in Python returns a property attribute. Syntax class property(fget=None, fset=None, fdel=None, doc=None) Parameter fget: This attribute is used for getting an attribute value. fset : This parameter sets an attribute value. fdel: It is a function for deleting...

1 minute read.

Python Goto Statement

We all know that Python is the most basic and widely used programming language in the world. It is also one of the world's most popular and widely used languages....

4 minutes read.

List in Python

What is List in Python In Python, lists are used to store the multiple values in one variable. We can say that list is the collection of similar as well as...

3 minutes read.

Socket Programming in Python

Socket Programming in Python In this tutorial, we will discuss network programming using Python programming language. We will explore all basic concept of network with Python script. Network Services in Python Python has...

9 minutes read.

Python print() function

Python print() function The print() function prints the specified message to the screen or other standard output devices. Syntax print(*objects,sep=' ',end='\n',file=sys.stdout,flush=False) Parameter objects: This function represents an object, which will be converted to a string...

1 minute read.

How to convert Float to Int in Python?

A float value can be converted to an int via type conversion, an explicit method of transforming an operand to a certain type. But it must be noted that such...

3 minutes read.

apply() function in python

Pandas: Pandas is a library in python. It is an open source package in python. Pandas in python are used for data cleaning and data analysis. Data frame mainly consists of...

3 minutes read.

Python Identifiers

Identifiers in Python User-defined names are identifiers in Python that are used to name variables, functions, classes, modules, and other things. You can create Python identifiers using these rules: As an identifier...

4 minutes read.

Working with files in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has an...

5 minutes read.

Matrix List Comprehension in Python

Introduction One of Python's most beautiful features is list comprehension. Iterating over an iterable object to create lists is a clever and succinct method. Nested List or matrix list Comprehensions, which...

6 minutes read.

Calculator Program in Python

Simple Calculator Program in Python This example helps to learn how to create a simple calculator program to perform operations like addition, subtraction, multiplication, and division. Source Code The following is the source...

2 minutes read.

Python Strong Number

Strong Number- Logic Divide each of the number's digits into separate units to determine if it is a strong number or not.The factorial of each digit must then be determined. The...

5 minutes read.

How to create a list in Python?

How to create a list in python Python is known for its versatility and its data structures help us to perform different kinds of operations on various datasets irrespective of their...

4 minutes read.

Cross Validation in Sklearn

Data scientists can benefit from cross-validation in machine learning in two key ways: it can assist in minimising the amount of data needed and ensure the artificial intelligence model is...

14 minutes read.

Python Line Break

Introduction In this tutorial, you will learn line breaks in python.In Python, the new line character is used to indicate the start of a new line and the end of an...

5 minutes read.

Python Parser

Introduction : Parsing is referred to as the processing and translation of a Python program into machine language. In general, we could indeed say that the command parse is used to...

4 minutes read.

Ternary operators in python

Starting from Python version 2.5, ternary operators are also known as Conditional operators. Using these operators, we can evaluate any problem based on a condition. It is an alternative and...

4 minutes read.

_dict_ in Python

An unordered collection of data values known as a dictionary can be used in Python to store data values similar to a map. Dictionaries can also store a key: value...

6 minutes read.