Find the bug · #2 · Off by one Easy Python
A 7-day report shows 6 days
A weekly sales report runs Monday to Sunday, but only ever shows six days.
On this page
The report
The weekly sales report covers Monday to Sunday. It always shows six days, and Sunday’s sales are never in it.
The code
Read it first: what should it do? Then click the line where you think the bug is.
from datetime import date, timedelta
def days_between(start, end):
"""Every day from start to end, both included."""
days = []
for i in range((end - start).days):
days.append(start + timedelta(days=i))
return daysRead it, then pick a line.
Monday the 23rd to Sunday the 29th: how many days apart are they, and how many days are there?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
week = days_between(date(2026, 11, 23), date(2026, 11, 29))
print(len(week))
print(week[-1])It prints
6 2026-11-28
It should print
7 2026-11-29
Show the answer: the bug, the fix, and how you’d find it
The bug (line 6)
Line 6 loops over range((end - start).days). Monday to Sunday is 6 days apart, so the loop runs for 0 to 5: six days, and Sunday is never added. Both ends are included, so the number of days is the difference plus one.
The fix
3def days_between(start, end):4 """Every day from start to end, both included."""5 days = []6 for i in range((end - start).days):6 for i in range((end - start).days + 1):7 days.append(start + timedelta(days=i))8 return daysHow you’d find it
- Reproduce with the reported week: Monday 23 to Sunday 29 November. You expect 7 days and get 6, ending on Saturday.
- Six instead of seven is one short, so check how the loop decides when to stop. The docstring says both ends are included.
- Count fence posts: 7 days have 6 gaps between them. The code counts the gaps, not the days.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
assert len(days_between(date(2026, 11, 23), date(2026, 11, 29))) == 7
assert days_between(date(2026, 11, 28), date(2026, 11, 28)) == [date(2026, 11, 28)]Where else this bites
- Hotel nights against days of a stay.
- “Pages 3 to 5” is three pages, not two.