Reading preferences
Concept

Recursion

Solve a smaller version of a problem, then follow how the answers return.

recursion, base case, call stack

A smaller version of the same job

Imagine counting a pile of cards. Put one card aside, count the smaller pile, then add one for the card you set aside. When no cards remain, the count is zero.

Recursion is when a function solves a problem by calling itself on a smaller version. A base case gives an answer without another call. Each call must move towards a base case; otherwise the calls will not finish.

Why use it and where it helps

Recursion is useful when a problem naturally contains smaller versions of itself. A folder may contain folders, and a tree can contain smaller trees. It also helps describe divide and conquer and backtracking. A loop is often simpler for a plain sum, so recursion is not automatically the best choice.

Follow the calls

Let sum_to(n) add the whole numbers from 1 through n, for a non-negative integer. Each call waits for the smaller answer before adding its own number.

sum_to(3) waits for 3 + sum_to(2)
sum_to(2) waits for 2 + sum_to(1)
sum_to(1) waits for 1 + sum_to(0)
sum_to(0) returns 0
Answers return: 0 -> 1 -> 3 -> 6

The unfinished calls are kept on a call stack: the most recent call finishes first, like the top plate in a stack.

See the reasoning

Follow the example one step at a time

Follow the calls and returns for sum_to(3). This is a prepared teaching demonstration, not live code execution.

Call sum_to(3)

3 + sum_to(2)

The call waits for the answer to a smaller problem.

Python illustration

def sum_to(n):
    if n == 0:
        return 0
    return n + sum_to(n - 1)


print(sum_to(3))
print(sum_to(0))

Prepared output — not live execution:

6
0

This teaching function assumes n is a non-negative integer. A negative number never reaches zero using this rule; validate input in a real program.

Time, space, and common mistakes

For n, this example makes n + 1 calls, taking O(n) time and O(n) call-stack space. Python limits recursion depth, so large inputs can raise RecursionError; a loop avoids this particular call-stack cost. Check both the stopping case and whether every recursive step can reach it.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. Why does a recursive function need a base case?
2. What happens to n in the recursive sum example?
3. What does sum_to(2) wait to add to 2?
4. What does sum_to(0) return in this example?

References and further reading