Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Recursion: Functions That Call Themselves

16 min 40 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 4 of 5 · View course roadmap
Step 1

Learn the idea

A recursive function solves a problem by solving a smaller copy of the same problem. Every correct one has exactly two parts:

  • Base case — an input so small the answer is immediate: if n < 10: return n
  • Recursive step — shrink the input and delegate: return n % 10 + digit_sum(n // 10)

The mental model: trust the recursive call. Don't trace every level — assume digit_sum(198) already works, and just add the last digit. If the base case is right and each step genuinely shrinks the input, the whole thing is right.

Recursion is the natural language of nested things: folders inside folders, JSON inside JSON, comments replying to comments.

Where you'll use this

File-tree walkers, JSON serialisers, comment threads, org charts, compilers — anything nested is naturally recursive. os.walk and json.dumps are recursion you already use.

Common mistakes

  • No reachable base case → RecursionError at ~1000 frames.
  • Forgetting return on the recursive call: digit_sum(n // 10) computes the value and throws it away — you need return n % 10 + digit_sum(...).
  • Recursing on the same input instead of a smaller one — shrinkage is what guarantees termination.

Pro tip

Trust the recursive call. Verify the base case, verify one step, and stop mentally unrolling five levels — that discipline is what makes recursion easy.

Step 2

Try it yourself

Blank · autosaved

The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.

PYexample.py
+ Enter to run
Output appears here…
Step 3

Pass the challenge +40 XP

Blank · autosaved

Write a recursive digit_sum(n) that adds up the digits of a non-negative number (digit_sum(1984) → 1+9+8+4 = 22). Print digit_sum(1984) and digit_sum(7).

Target output
22
7
PYchallenge.py
Run your code to check it…
Step 4

Check your understanding

1. What happens to a recursive function with no (reachable) base case?
2. In digit_sum, why must the recursive call use n // 10?
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path