Write a Recursive Factorial Function in Python

Define a recursive factorial function that handles edge cases and returns the product of all positive integers up to n.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 14 views 0 copies

Python code

10 lines
Python 3.9+
def factorial(n):
    """Return the factorial of n using recursion."""
    if n < 0:
        raise ValueError("Factorial is not defined for negative numbers")
    if n == 0 or n == 1:
        return 1
    return n * factorial(n - 1)

if __name__ == "__main__":
    print(factorial(5))

Output

stdout
120

How it works

The function checks for negative input and raises a ValueError to prevent invalid recursion. The base case returns 1 when n is 0 or 1, stopping the recursion. Each recursive call multiplies n by the factorial of n-1, breaking the problem into smaller subproblems. This works because every recursive call reduces n, so the base case is eventually reached. In the main block, factorial(5) returns 54321 = 120 and prints it.

Common mistakes

  • Forgetting the base case, which causes infinite recursion and a RecursionError
  • Not handling negative numbers, leading to infinite recursion with negative n
  • Using an iterative loop instead of recursion, defeating the purpose
  • Placing the base case after the recursive call, so it never executes

Variations

  1. Use functools.lru_cache to memoize results for repeated calls
  2. Write an iterative version using a loop for efficiency on large n

Real-world use cases

  • Calculating permutations and combinations in probability and combinatorics scripts.
  • Implementing recursive algorithms like generating permutations or combinations where factorial is a core step.
  • Estimating factorials in statistical formulas such as probability mass functions for small n.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.