Lesson 22 / 49

Recursion

Solve problems with recursive functions using a base case, and know Python's recursion depth limit.

Base case + recursive step

Every recursive function needs a base case to stop, and a step that moves toward it.

def factorial(n):
    if n <= 1:          # base case
        return 1
    return n * factorial(n - 1)  # recursive step

print(factorial(5))   # 120

Recursion limits

Python's default recursion limit is ~1000 calls deep. For simple counting loops, an ordinary for/while is usually clearer and faster.