Fix the Off-by-One Bug
Beginner · Fix the bug · from Program Design and Testing: Plan, Build and Debug Code
From the lesson: Program Design and Testing: Plan, Build and Debug Code
Every app on your phone began as an idea that people turned into a working program by planning it, building it in small steps, and testing it until it did what its users needed. That app is a computing innovation: something new that depends on a program to do its job.
Read the lessonA reading-log app counts how many pages you read. Reading from page 10 to page 12 means you read pages 10, 11 and 12, which is 3 pages. The function below returns 2 instead. Find the off-by-one error and fix it.
pages_read(10, 12) -> 3
pages_read(5, 5) -> 1def pages_read(first_page, last_page):
count = 0
page = first_page
while page < last_page:
count += 1
page += 1
return count
What Check runs
Your code runs first, then each of these lines, and 1 more that stay hidden. The output must match exactly.
| Runs | Expected output |
|---|---|
| print(pages_read(10, 12)) | 3 |
| print(pages_read(5, 5)) | 1 |
| print(pages_read(1, 300)) | 300 |
More Program Design exercises
- Handle Volume Button EventsBeginner
- Write Tests That Catch the BugIntermediate