A smaller version of the question.
Solve a problem by reducing it, and prove there is a way to stop.
01 The idea
A recursive function calls itself on a smaller problem. It needs a base case and a progress argument: each call must move toward a terminating condition. The call stack stores unfinished work, so recursion has a space cost and a practical depth limit in Python. Iterative code is often simpler for flat repetition.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
def factorial(number):
if number < 0:
raise ValueError("number must be nonnegative")
if number == 0:
return 1
return number * factorial(number - 1)
print(factorial(5))
print(factorial(0))120 1
03 Under the hood
- 1
The base case factorial(0) returns without another recursive call. The mathematical convention makes zero factorial one.
- 2
Each positive call reduces its input by one, leaving a multiplication waiting on the stack. Time and stack space are linear in the input in this implementation.
- 3
For deep input, a loop avoids recursion-depth limits. Increasing the recursion limit is not a general fix for an algorithm that consumes excessive stack space.
04 Your turn, builder
Implement iterative factorial and compare it with the recursive result for 5.
Reveal one possible solution +
def factorial(number):
result = 1
for value in range(2, number + 1): result *= value
return result
print(factorial(5))05 Check your signal
What must a recursive algorithm have?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.