Edge cases
Python · Unit 20: Testing and debugging
- Full plan
- Python
- 9 exercises
The happy case almost always works: that is the one we try. Bugs live at the extremes.
The empty list, zero, a negative number, the empty string and the single element are the five usual suspects.
def average(ns):
return sum(ns) / len(ns)
print(average([6, 8]))
try:
print(average([]))
except ZeroDivisionError as e:
print("Crash:", e)Prints
7.0 Crash: division by zero
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Find the case that fails
initial(t)should return the first letter of the name in uppercase, and an empty string when there is no name. Which call breaks it?3. Complete the code
Complete the guard so the empty list gives 0.
4. Complete the code
Complete it so the function returns 0 when there is no square root to take.
5. Find the case that fails
percent(part, whole)should return what percentagepartis of the whole, and 0 when the whole is 0. Which call breaks it?6. Find the bug
This function should return the average, and 0 only when the list is empty. Which line has the error?
7. Predict the output
What does this code print?
8. Put the lines in order
Put the function in order so the empty list does not crash it.
9. Multiple choice
You just wrote
initial(t), which returns the first letter of a name. Which input would you try first?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.