Browse Python Topics ▼
Pick a Web Framework

Recursion and the Call Stack

📂 Functions & Modular Code 📘 Lesson 26 of 57

Master recursive thinking in Python. Understand base cases, recursive steps, the execution call stack, recursion limits, and tree traversal.

Imagine holding a set of Russian nesting dolls (Matryoshka dolls).

You open the largest doll, and inside you discover a slightly smaller doll. You open that doll, and find an even smaller one. You repeat this exact same action over and over until you reach the tiny, solid wooden doll at the center.

Because the smallest doll is solid and cannot be opened, you stop opening dolls. You then snap all the outer dolls back together one by one.

In computer science, this problem-solving technique is called Recursion. A function is recursive when it solves a large problem by breaking it into smaller instances of the same problem and calling itself.


1. The Two Golden Rules of Recursion

Every functional recursive function must possess two non-negotiable components:

  1. The Base Case: The simplest possible condition that returns a concrete answer directly without making another recursive call (the solid wooden doll).
  2. The Recursive Step: The logic that shrinks the problem and invokes the function again with a smaller, simpler input moving toward the base case.
def countdown(seconds):
    # 1. BASE CASE (Stop condition)
    if seconds <= 0:
        print("Blastoff! Rocket has launched.")
        return

    # 2. RECURSIVE STEP (Progress toward base case)
    print(f"{seconds}...")
    countdown(seconds - 1)  # Function calls itself with a smaller number!

countdown(3)

Output:

3...
2...
1...
Blastoff! Rocket has launched.

What Happens Without a Base Case?

If you forget the base case, or if your recursive step fails to shrink the input, Python calls the function indefinitely until memory fills up:

def endless():
    endless()

# endless()
# RecursionError: maximum recursion depth exceeded

2. Classic Example: Factorial ($n!$)

The factorial of a non-negative integer $n$ (written $n!$) is the product of all positive integers less than or equal to $n$: $$5! = 5 \times 4 \times 3 \times 2 \times 1 = 120$$

Notice the recursive pattern: $$5! = 5 \times 4!$$ $$4! = 4 \times 3!$$ $$3! = 3 \times 2!$$ $$2! = 2 \times 1!$$ $$1! = 1 \quad (\text{Base case})$$

Here is how that translates directly into Python:

def factorial(n):
    # Base case: 0! and 1! are both 1
    if n <= 1:
        return 1
    
    # Recursive step: n * factorial(n - 1)
    return n * factorial(n - 1)

print("5! =", factorial(5))  # 120

3. The Call Stack Demystified

To truly understand recursion, you must visualize what happens inside your computer’s RAM.

Whenever a function is invoked, Python pushes a stack frame onto the Call Stack (like adding a plate to a stack of plates in a cafeteria):

CALLING DOWN (Winding the stack):
  factorial(5) pauses, waiting for factorial(4)
    factorial(4) pauses, waiting for factorial(3)
      factorial(3) pauses, waiting for factorial(2)
        factorial(2) pauses, waiting for factorial(1)
          factorial(1) hits base case! Returns 1.

RETURNING UP (Unwinding the stack):
        factorial(2) receives 1  ──► computes 2 * 1  ──► returns 2
      factorial(3) receives 2    ──► computes 3 * 2  ──► returns 6
    factorial(4) receives 6      ──► computes 4 * 6  ──► returns 24
  factorial(5) receives 24       ──► computes 5 * 24 ──► returns 120

Notice that none of the outer functions can finish until the inner function hits the base case and unwinds!


4. Python’s Recursion Limit

To protect your system from exhausting all available RAM and crashing the operating system, Python enforces a strict stack depth limit:

import sys

print("Default recursion limit:", sys.getrecursionlimit())  # Typically 1000

If your function calls itself more than 1,000 times without reaching a base case, Python deliberately halts execution with a RecursionError.

[!NOTE] Unlike languages like Scheme, Haskell, or Scala, Python does not implement Tail-Call Optimization (TCO). Python’s creator, Guido van Rossum, explicitly chose not to include TCO so that full, accurate stack traces remain available whenever an error occurs.


5. Recursion vs Iteration: When to Use Which?

Complete beginners often wonder: “Can’t I just use a for or while loop instead?”

Yes! In fact, any problem that can be solved with recursion can also be solved iteratively.

CriteriaIteration (for / while)Recursion
Memory usage$O(1)$ constant memory$O(n)$ stack frames in RAM
Speed in PythonFaster (no call frame overhead)Slower (function call overhead)
Best suited forLinear sequences, counting, simple listsTrees, nested directories, graphs, JSON

When Recursion Shines: Navigating Nested Data

Consider calculating the total file count inside a folder containing arbitrary subfolders and sub-subfolders. Writing that with flat loops requires manual stack management. With recursion, it is effortless:

# A simulated nested file directory
file_system = {
    "Documents": {
        "Resume.pdf": 1,
        "Projects": {
            "app.py": 1,
            "test.py": 1
        }
    },
    "Photos": {
        "vacation.png": 1
    }
}

def count_files(folder):
    total = 0
    for name, content in folder.items():
        if isinstance(content, dict):
            # It's a subfolder: recursively count files inside!
            total += count_files(content)
        else:
            # It's a file
            total += 1
    return total

print("Total files across all nested folders:", count_files(file_system))  # 4

Summary & Stage 6 Capstone

Congratulations on completing Stage 6: Functions & Modular Code! You have mastered:

  • Reusable modular logic with def, arguments, and return in functions.
  • Variable visibility, namespaces, and the LEGB rule.
  • Variadic, dynamic parameter handling using args-kwargs.
  • Quick inline anonymous transformations using lambdas.
  • Self-referential problem solving and stack frames in Recursion.

Next, learn how to defend your programs against bugs, crashes, and invalid inputs in Stage 7, starting with errors.

Test your understanding of Recursion and the Call Stack

Quick interactive practice questions with instant feedback.

Take Quiz →