Chapter 10
Errors, Validation, and Debugging
Errors Have Different Shapes
You met errors in Chapter 1. You deliberately caused a
Now you can organize those experiences into three useful categories. The category tells you where to begin looking.
1. Python cannot understand the code
A syntax error means the code does not follow Python’s grammar:
if temperature > 20
print("Warm day")
The missing colon prevents Python from starting the program. Python reports a SyntaxError before the intended work can happen.
Check punctuation, indentation, paired quotes, and paired brackets near the reported line. The marker is a clue, but the real mistake can be just before it.
2. Python starts, then an operation fails
A
distance = 12
hours = 0
print(distance / hours)
Python understands every line, but division by zero is not a valid operation. It stops with a ZeroDivisionError.
Other exceptions you have already encountered include:
NameErrorfor a name that has not been defined;ValueErrorwhen acannot be converted as requested; KeyErrorwhen bracket lookup asks afor a missing key.
An exception has a type and a message. Both help you investigate.
3. The program runs but gives the wrong result
Sometimes Python reports no exception:
price = 8
quantity = 3
total = price + quantity
print(total)
The program prints 11, but a shop total should be 24. This is a logic bug: valid Python did something different from the requirement.
Because there is no
Name the symptom before changing code
Ask:
Did Python reject the code before it ran?
Did the program stop with an exception?
Did it finish with the wrong behavior?
These categories are not judgments about how serious a bug is. A one-character logic bug can be costly, while a long traceback can point to a quick fix. The categories simply give your investigation a useful first direction.
A program runs to completion, but a discount is added to the price instead of subtracted. What kind of problem is this?
What happens when this program runs?
number = int("twelve")
print(number)