A function that calls itself
Recursion means solving a problem by calling the same function on something smaller. Every recursive function needs a base case — the version it can answer immediately — or it calls itself forever.
def countdown(n):
if n <= 0: # base case: stop here
print("Liftoff!")
return
print(n)
countdown(n - 1) # the same problem, one smaller
Factorial: the classic
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120
Read it as: 5! is 5 × 4!, and 4! is 4 × 3!, down to 1! which is 1. Each call waits for the answer from the smaller one.
When to reach for it
Recursion is not always the fastest option, but for anything defined in terms of itself — folders inside folders, family trees, a maze — it is usually the clearest. If a problem feels like "the same thing, but smaller", it is a recursion problem.