BeginnerCoder

Lesson 6 — Recursion: factorial

Recursion: a function that calls itself

Recursion solves a problem by solving a smaller version of the same problem. It needs two parts: a base case that answers directly (so it stops), and a recursive case that calls the function on a smaller input. Factorial is the classic: 5! = 5 × 4 × 3 × 2 × 1, which is 5 × 4!.

# fact(3) = 3 * fact(2) = 3 * 2 * fact(1) = 3 * 2 * 1 = 6

Watch out: forget the base case and the function calls itself forever until Python stops it with a RecursionError.

Why it matters: trees, folders and many "divide and conquer" algorithms are naturally recursive.

Want it another way?
Task

Write the recursive case: return n times fact(n - 1). Expected: factorials of 1 to 5.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.