DEV Community

Harini
Harini

Posted on

Recursion in Python: Factorial with Debugging Explained

What is Recursion?

Recursion is a technique where a function calls itself to solve a problem step by step.

Instead of using loops, recursion breaks a problem into smaller subproblems.

Factorial Using Recursion

Factorial of a number means:

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

Python Code

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

print(factorial(5))
Enter fullscreen mode Exit fullscreen mode

Debugging the Code (Step-by-Step Execution)
Let’s trace what happens when we call:

factorial(5)
Enter fullscreen mode Exit fullscreen mode

Function Calls

factorial(5)
= 5 * factorial(4)

factorial(4)
= 4 * factorial(3)

factorial(3)
= 3 * factorial(2)

factorial(2)
= 2 * factorial(1)

factorial(1)
= 1   (Base Condition)

Enter fullscreen mode Exit fullscreen mode

Returning Values (Backtracking)


factorial(2) = 2 * 1 = 2
factorial(3) = 3 * 2 = 6
factorial(4) = 4 * 6 = 24
factorial(5) = 5 * 24 = 120

Enter fullscreen mode Exit fullscreen mode

Understanding the Debugging Flow

Recursion has 2 important parts:

1. Base Case

if n == 1:
    return 1
Enter fullscreen mode Exit fullscreen mode

Stops the function from running forever.

2. Recursive Case

return n * factorial(n - 1)
Enter fullscreen mode Exit fullscreen mode

Function calls itself with a smaller value.

Common Debugging Mistakes

  • Missing base case → Infinite recursion
  • Wrong condition (like n == 0 vs n == 1)
  • Forgetting return statement
  • Large input → Stack Overflow error

Top comments (0)