logo

Understanding Recursion in Python

O

Ohidur Rahman Bappy

MAR 22, 2025

Understanding Recursion in Python

A function that calls itself is known as a recursive function. This method is often used when a problem can be defined in terms of smaller instances of itself. Although recursion involves iteration, using a recursive approach can provide concise solutions to complex problems.

The most classic example of recursion is calculating a factorial. The factorial of a number, n, is mathematically defined as: n! = n × (n-1)!

Factorial Example

In the case of factorial, recursion is ideal since we use the factorial itself in its definition. Let's expand this using the example of calculating the factorial of 5:

5! = 5 × 4!
   = 5 × 4 × 3!
   = 5 × 4 × 3 × 2!
   = 5 × 4 × 3 × 2 × 1!
   = 5 × 4 × 3 × 2 × 1
   = 120

While these calculations can be performed using loops, recursion simplifies the solution into successive function calls. Here's how you can define a recursive function to calculate factorials:


def factorial(n):    
    if n == 1:
        print(n)
        return 1    
    else:
        print(n, '*', end=' ')
        return n * factorial(n-1)

Calling the Recursive Function

The recursive factorial function can be invoked as shown below:

>>> factorial(5)
5 * 4 * 3 * 2 * 1
120

In this example, calling factorial(5) results in successive calls to the function with decreasing values. The function begins to return once the argument reaches 1. The first call's return value is a cumulative product of all returned values from subsequent calls.