0%

Chapter 10

Errors, Validation, and Debugging

Errors Have Different Shapes

You met errors in Chapter 1. You deliberately caused a , repaired a misspelled name, and learned to read the final line of an error message first.

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 happens while Python is running valid syntax:

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:

  • NameError for a name that has not been defined;

  • ValueError when a cannot be converted as requested;

  • KeyError when bracket lookup asks a for 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 , compare the actual result with a small result you can calculate yourself. Then inspect the values and operations that produced it.

Name the symptom before changing code

Ask:

  1. Did Python reject the code before it ran?

  2. Did the program stop with an exception?

  3. 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)