Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Think in algorithms
EXPERIMENT 62 / 101

A smaller version of the question.

Solve a problem by reducing it, and prove there is a way to stop.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

01 The idea

A recursive function calls itself on a smaller problem. It needs a base case and a progress argument: each call must move toward a terminating condition. The call stack stores unfinished work, so recursion has a space cost and a practical depth limit in Python. Iterative code is often simpler for flat repetition.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

recursion.py
def factorial(number):
    if number < 0:
        raise ValueError("number must be nonnegative")
    if number == 0:
        return 1
    return number * factorial(number - 1)
print(factorial(5))
print(factorial(0))
↳ EXPECTED OUTPUT
120
1

03 Under the hood

  1. 1

    The base case factorial(0) returns without another recursive call. The mathematical convention makes zero factorial one.

  2. 2

    Each positive call reduces its input by one, leaving a multiplication waiting on the stack. Time and stack space are linear in the input in this implementation.

  3. 3

    For deep input, a loop avoids recursion-depth limits. Increasing the recursion limit is not a general fix for an algorithm that consumes excessive stack space.

04 Your turn, builder

A SMALL MISSION

Implement iterative factorial and compare it with the recursive result for 5.

Reveal one possible solution +
one_possible_solution.py
def factorial(number):
    result = 1
    for value in range(2, number + 1): result *= value
    return result
print(factorial(5))

05 Check your signal

QUICK SIGNAL CHECK

What must a recursive algorithm have?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.