BeginnerCoder

Lesson 5 — Spot the bug: off-by-one

The most common bug in the world

An off-by-one bug gives an answer that is wrong by exactly one: one page too few, one item skipped, a loop that stops early. AI assistants write them too, because the code looks right.

Example: how many pages do you need to show 11 items, 5 per page? 11 // 5 is 2 — but the 11th item needs a third page. You need to round up:

(items + per_page - 1) // per_page   # rounds up without floats

To find off-by-one bugs, test the boundaries: exactly full (10 items), one more (11), less than one page (4), and zero.

Why it matters: boundary tests take a minute to write and catch the bug that "looks right" in every code review.

Want it another way?
Task

The AI's page_count() is off by one when items do not fill the last page. Fix it so all four lines are correct (11 items → 3 pages, 0 items → 0 pages).

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.