Skip to content
Minute Campus.

Almost rightLesson 011 min

This loop looks right. It skips one item

A function meant to add up prices returns 30 for 5, 10 and 20, with no error or warning. The loop counts from one, but Python numbers a list from zero, so the first price is never added. This is an off-by-one error. The fix is to loop over the prices themselves, so there is no start or end to get wrong.

Remember

Test code that returns a number on a small case you can work out by hand.

Transcript

The lesson, word for word.

Read it at your own pace, or search the page for a term.

This loop looks right. It skips one item. You have three seconds to find it. The function is meant to add up a list of prices. Five, ten and twenty should give thirty-five. It gives thirty. No error, no warning. Just a wrong total. Here is the faulty line. The loop counts from one to the end of the list. But Python numbers a list from zero. So the first price, at position zero, is never added. This is an off-by-one error, and it is easy to miss because the code runs without complaint. The fix is to stop counting by hand. Loop over the prices themselves, and there is no start or end to get wrong. The rule: when code gives you a number, test it on a small case you can work out in your head. In this series, the code is almost right, and there is one bug to find.

Questions? Comment on the lesson on YouTube

New lessons every day.

Follow Minute Campus where you already scroll.