Recursion in Python. Topic-21

Recursion in Python

Recursion is a concept of Python programming language, where the function calls itself in its definition. In Python programming, a recursive function is a function, that calls itself by its execution time.

There are three main concepts that you need to understand these concepts:

  • for loop
  • if else statement
  • function

If you don’t know these concepts, then please read these topics first. Without these topics, you cannot understand the recursion function.

So, let’s see some examples to understand this. First, we will see what we can do without recursion. There we use the example of factorial to understand recursion.

Factorial Without Recursion:

def factorial(n):
    result = 1
    for i in range(1, n + 1):
        result = result * i
    return result

# Example usage:
number = 5
result = factorial(number)

The Output Of This Code Will Be:


Example: Factorial using Recursion:

def factorial(n):
    if n == 0 or n == 1:
        return 1
        return n * factorial(n - 1)

# Output
result = factorial(5)

Key Concept:

factorial(5) = 5 * factorial(4)
factorial(4) = 5 * 4 * factorial(3)
factorial(3) = 5 * 4 * 3 * factorial(2)
factorial(2) = 5 * 4 * 3 * 2 * factorial(1)
factorial(1) = 5 * 4 * 3 * 2 * 1

The Output Of This Code Will Be:


Iteration-1: At first we call factorial(5) and pass an argument. Now the value of ‘n’ is 5. If the ‘n’ value is greater than 1 then the recursive function will call. Now program control is next to the else block.

Iteration-2: return 5 * factorial(4) happens.

  • The value of n is 4, and it doesn’t satisfy the base case, so we move to the recursive case.
  • return ‘5 * 4 * factorial(3)‘ happens.

Iteration-3: return 4 * 3 * facto(2) happens.

  • Next, we call factorial(2).
  • The value of n is 2, and it doesn’t satisfy the base case, so we move to the recursive case.
  • return ‘4* 3 * 2 * facto(1)‘ happens.

Iteration-4: return 5 * 4 * 3 * 2 * factorial(1) happens.

  • Now, we call factorial(1).
  • We reach the base case because the value of ‘n’ is 1, and return 1 occurs

If you don’t know the “Docstrings in Python” just click on Read More.

I hope you understand “Recursion in Python” Need guidance or have questions? Drop a comment below. Share your email for a personalized touch—I’ll send exclusive resources and answer queries. Let’s code together, creating efficient code and memorable learning moments! 🚀

Finite number of  lines code and infinite possibilities

Programmer, Arpan Bera

Leave a Reply

Your email address will not be published. Required fields are marked *

Arpan Bera

Coding is like Love – everyone can start, but only a few finish without errors

Keep Updated to our News and Blog