Skip to content
Minute Campus.

Almost rightLesson 021 min

It works for the example and breaks on an empty list

A function that averages a list works for two, four and six, so it gets approved. Then a new user has no scores. The function adds nothing, divides by a length of zero, and Python stops with a division by zero error. The code was only tried with the input its author imagined. The fix starts with deciding what the average of nothing should be.

Remember

Try a function with empty input and one item before trusting it.

Transcript

The lesson, word for word.

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

It works for the example and breaks on an empty list. Three seconds: where? This function returns the average of a list of scores. Give it two, four and six, and it returns four. Correct. So it gets approved. Then one day a new user has no scores yet. The list is empty. The function adds up nothing, gets zero, and divides by the number of scores, which is also zero. Python stops with a division by zero error, and the page crashes. The code was only ever tried with the input its author imagined. The fix starts with a decision, not with code. What should the average of nothing be? Here, the function returns no value at all, and the page can say: no scores yet. The rule: before you trust a function, try it with empty input and with a single item. The example in the prompt is never the only case.

Questions? Comment on the lesson on YouTube

New lessons every day.

Follow Minute Campus where you already scroll.