Lesson 24
Recursion
A recursive function calls itself on a smaller input. Every recursive function needs a base case that stops the calls.
factorial(4) is 4 * factorial(3), and so on until factorial(1), which simply returns 1.
Deep recursion uses memory and Python limits its depth. Use loops when the repetition is simple.
def countdown(n):
if n == 0:
return
print(n)
countdown(n - 1)Check your understanding
What stops a recursive function?
CHALLENGE
Define factorial(n) recursively, with factorial(1) returning 1. Print factorial(5).
Practice →