Editor

Factorial with recursion in Python

The factorial of n is n × (n - 1) × ... × 1. A recursive function works it out by calling itself on a smaller number until it reaches 1, then multiplying on the way back.

The arrow keys step through it. Edit the code to try your own input.

How it works

  1. factorial(5) calls factorial(4), which calls factorial(3), and so on. Each call gets its own frame with its own n.
  2. When n reaches 1, the base case returns 1 without calling again.
  3. Each waiting frame then receives its smaller result, multiplies it by its own n and returns.
  4. The answers flow back up the stack: 1, 2, 6, 24, 120.

What to watch

  • Watch five factorial frames stack up, each with a different n.
  • Watch smaller appear in each frame as the calls return, starting from the deepest one.
  • Watch the frames disappear one by one, each returning n * smaller to the frame below it.

The code

def factorial(n):
    if n <= 1:
        return 1                 # base case: stop calling
    smaller = factorial(n - 1)   # wait for the smaller problem
    return n * smaller

print("5! =", factorial(5))
Output
5! = 120

Open it in the editor · Python Program to Find the Factorial Using Recursion, explained