Python Recursion · Exercises
Core Python

Python Recursion Exercises

4 exercises that build on the Python Recursion lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: Recursion is when a function solves a problem by calling itself on a smaller version of that problem, stopping at a base case that it can answer directly. By the end you can write a recursive function with a base case and a recursive case, follow the call stack, speed up repeated work with functools.cache, handle nested data, avoid RecursionError, and decide when a loop is the better choice. You will practise: Add up 1 to n; Predict down and up; Fix the power function; How deep does a list nest?.

0 / 4 completed

Python Recursion practice exercises

1. Add up 1 to n

Write code Easy

Write a recursive function sum_to(n) that returns 1 + 2 + ... + n. sum_to(0) should return 0. Do not use a loop and do not use the formula n * (n + 1) // 2: the function must call itself. Then print sum_to(5).

Your code
def sum_to(n):
    # base case: what is the sum when n is 0?
    # recursive case: n plus the sum up to n - 1
    pass

print(sum_to(5))

2. Predict down and up

Predict the output Easy

This function prints once before the recursive call and once after it. Type exactly what the program prints, then press Check.

Read this code
def show(n):
    if n == 0:
        return
    print("down", n)
    show(n - 1)
    print("up", n)

show(3)

3. Fix the power function

Fix the bug Medium

power(base, exp) should return base multiplied by itself exp times, so power(2, 5) is 32 and the program should print 32. Instead it crashes with a RecursionError. Fix the bug.

Your code
def power(base, exp):
    if exp == 0:
        return 1
    return base * power(base, exp)

print(power(2, 5))

4. How deep does a list nest?

Write code Hard

Write a recursive function depth(items) that returns how many levels of lists are nested inside items.

  • A list with no lists inside it has depth 1 (an empty list too).
  • [1, [2, 3]] has depth 2, and [1, [2, [3]]] has depth 3.

Only lists count as nesting; other values (numbers, strings) add nothing. Then print depth(data) for the given data.

Your code
def depth(items):
    # 1 for this list, plus the deepest list found inside it
    pass

data = [1, [2, [3, [4]]], [5, 6]]
print(depth(data))

Next lessonPython Variable Scope

More Python Recursion examples · All Python exercises