Quick Concepts

Recursion Explained With Everyday Examples

Recursion explained through nesting dolls, folders and countdowns, with a clear look at base cases, the call stack and when to use loops instead.

On this page
  1. The Nesting Doll Idea
  2. A Countdown in Code
  3. Folders Inside Folders
  4. What Happens Behind the Scenes
  5. Recursion Versus Loops
  6. Tips for Writing Recursive Functions
  7. Frequently Asked Questions

Recursion has a reputation for being confusing, and the usual definition does not help: a function that calls itself. That sentence is accurate, but it explains nothing about why you would want one or how it ever finishes. A better way in is through situations you already know from daily life.

Once the pattern clicks, you will see it everywhere, from folders inside folders to menus with sub-menus. This article walks through a few of those examples and then shows the same ideas in code.

The Nesting Doll Idea

Picture a set of wooden nesting dolls. You want to know how many dolls are in the set. You open the largest doll. If there is another doll inside, you repeat the same task on that smaller doll: open it, check for another one inside. Eventually you open a doll that is empty, and you stop.

This captures the two parts every recursive solution needs.

  • A base case: the situation simple enough to answer directly. Here it is the empty doll.
  • A recursive case: the situation where you reduce the problem to a smaller version of itself. Here it is "there is a doll inside, so do the same thing again."

Without a base case, the process never ends. With a recursive case that does not shrink the problem, it also never ends. Getting both right is the whole craft.

A Countdown in Code

The smallest useful example is a countdown. To count down from 3, say 3, then count down from 2, and so on until you reach 0.

def countdown(n):
    if n == 0:
        print("Done")
        return
    print(n)
    countdown(n - 1)

countdown(3)

This prints 3, 2, 1, and then Done. The check n == 0 is the base case. The call countdown(n - 1) is the recursive case, and each call hands the function a smaller number. Because n shrinks every time, it must eventually hit the base case.

Folders Inside Folders

A more realistic example is a folder on your computer. A folder holds files and other folders, and those hold more files and folders, to any depth. Suppose you want to add up the size of everything inside a folder.

You do not know how deep the nesting goes, so a fixed number of loops will not work. But the logic is easy to state: the size of a folder is the size of its files plus the size of each sub-folder, and the size of each sub-folder is found the same way.

import os

def folder_size(path):
    total = 0
    for entry in os.scandir(path):
        if entry.is_file():
            total += entry.stat().st_size
        elif entry.is_dir():
            total += folder_size(entry.path)
    return total

The base case is hidden but present: a folder with no sub-folders makes no further recursive calls. Each recursive call works on a smaller part of the tree, so the process ends.

What Happens Behind the Scenes

Each time a function calls itself, the computer keeps track of where it was, so it can come back. These records are stored in the call stack. When countdown(3) calls countdown(2), the first call waits. It resumes only after the inner call returns.

You can think of it like a stack of sticky notes. Each call adds a note, and each return removes the top one. Two practical consequences follow:

  • Recursion uses memory for every pending call. Going extremely deep can exceed the limit and cause an error, often called a stack overflow.
  • Many languages cap the recursion depth. Python, for example, has a default limit of about a thousand nested calls.

This is why a missing base case is dangerous. The function keeps adding notes to the stack until the program stops with an error.

Recursion Versus Loops

Anything you can do with recursion you can also do with a loop, and the reverse is true too. So when should you choose recursion?

Recursion fits best when the data itself is nested or branching. Trees, folder structures, nested comments, JSON documents, and puzzles with several choices at each step all have a natural recursive shape. The code often reads almost like a description of the problem.

A plain loop is better for simple repetition, such as adding up a list of numbers. It uses less memory and avoids depth limits. If you find yourself writing a recursive function that only ever calls itself once at the end, a loop is probably clearer.

Tips for Writing Recursive Functions

  1. Write the base case first. Decide what the simplest input is and what the answer is for it.
  2. Make sure each recursive call moves closer to the base case, for example by using a smaller number or a shorter list.
  3. Trust the function. When writing the recursive step, assume the call on the smaller problem already works, and only think about how to combine its result with the current step.
  4. Test with tiny inputs first, such as zero, one, and two items.

The third tip is the mental shift that makes recursion feel easy. You do not need to trace every level in your head. You only need to be sure about one step and the base case.

Frequently Asked Questions

Why does my recursive function crash with a maximum depth error?

Either the base case is missing or wrong, or the input never gets smaller, so the calls never stop. Check that each call moves toward the base case. If your data is legitimately very deep, switch to a loop.

Is recursion slower than a loop?

Often slightly, because each call has overhead and uses stack memory. For most everyday tasks the difference is not noticeable. Choose the version that is clearer for the problem.

Do I really need recursion in everyday programming?

Not constantly, but it appears whenever you handle nested data such as folders, trees, or nested JSON. Understanding it also helps you read code in libraries and algorithms like merge sort that depend on it.