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
factorial(5)callsfactorial(4), which callsfactorial(3), and so on. Each call gets its own frame with its ownn.- When
nreaches 1, the base case returns 1 without calling again. - Each waiting frame then receives its
smallerresult, multiplies it by its ownnand returns. - The answers flow back up the stack: 1, 2, 6, 24, 120.
What to watch
- Watch five
factorialframes stack up, each with a differentn. - Watch
smallerappear in each frame as the calls return, starting from the deepest one. - Watch the frames disappear one by one, each returning
n * smallerto 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