A-level Python · Lesson 1 of 9

Recursion and call stacks

OCR H446 algorithms / AQA 7517 recursion

Write a recursive factorial function with a base case.

← All A-level Python lessons

Understanding recursive calls

Recursion solves a problem by calling the same function on a smaller input. Every recursive solution needs a base case that stops further calls. Trace each call and the values returned as the call stack unwinds.

Watch out: A missing or unreachable base case leads to repeated calls until Python raises a recursion error.

1 · Learn and explore

Study this example, identify inputs and outputs, then trace the key variables. Run and adapt it in Python 3.

def factorial(n):
    if n < 0: raise ValueError("n must be non-negative")
    if n <= 1: return 1
    return n * factorial(n-1)

2 · Independent programming challenge

Write a recursive factorial function with a base case. Download the starter, design your solution, and add tests before revealing the answer.

Download starter + solution ZIP ↓

Stretch task: investigate time/space complexity or data validation, then write an evaluation of your approach.

Show reference solution after attempting the task
def factorial(n):
    if n < 0: raise ValueError("n must be non-negative")
    if n <= 1: return 1
    return n * factorial(n-1)

assert factorial(0) == 1
assert factorial(5) == 120
print(factorial(5))

3 · Debug and explain

Change one boundary condition in the starter or reference program. Predict which test fails, then repair it and document why.

Concept check: What happens if a recursive function has no reachable base case?

Reveal explanation

It eventually raises RecursionError because calls continue until the call-stack limit.

4 · Assess your learning

Describe the algorithm or design in your own words; include a normal test, a boundary test and an invalid input. Compare your answers with the reference solution and record one improvement.

Progress is stored only in this browser.

Want extra practice? Try interactive Python tracing and debugging questions →