All programmers make mistakes, every day. The difference between a beginner and a professional is that the professional knows how to read what Python says and looks for the cause with method.
The three types of error
| Type | When it appears | Example |
|---|---|---|
| Syntax | Before running: Python does not understand the code | A missing : or parenthesis |
| Runtime (exception) | While running: something impossible | Dividing by zero, using an index that does not exist |
| Logic | It never warns: the program works, but gives a wrong result | A > condition that should have been >= |
The first two are detected automatically. Logic errors are the hardest: nobody warns you, which is why you need tests.
Syntax errors
# if age >= 18
# print("adult")
#
# SyntaxError: expected ':'
Python indicates the line and usually points to the problem. Also check the previous line: an unclosed parenthesis there causes the error on the next one.
Exceptions and traceback
When an exception is not caught, Python prints a traceback: the path the program followed until the error.
def divide(a, b):
return a / b
def calculate(x):
return divide(x, 0)
print(calculate(10))
# Traceback (most recent call last):
# File "main.py", line 7, in <module>
# print(calculate(10))
# File "main.py", line 5, in calculate
# return divide(x, 0)
# File "main.py", line 2, in divide
# return a / b
# ZeroDivisionError: division by zero
It is read from bottom to top:
- The last line is the error: the type (
ZeroDivisionError) and the message (division by zero). - The
Fileline just above indicates where it happened: file, line number and function (divide). - The previous lines are the chain of calls that led there:
<module>calledcalculate, and this one calleddivide.
With this you know what failed and where. To know why, you have to look at which values reached that line. Practice with Read a traceback.
The most common exceptions
| Exception | Typical cause |
|---|---|
NameError | Using a variable that does not exist (or is misspelled) |
TypeError | Operating with incompatible types: 3 + "a" |
ValueError | Value of the right type, but inappropriate: int("abc") |
IndexError | Position out of range in a list |
KeyError | Key that does not exist in a dictionary |
AttributeError | Asking for an attribute or method that the object does not have |
ZeroDivisionError | Dividing by zero |
IndentationError | Incorrect indentation |
data = {"name": "Ana"}
try:
print(data["age"])
except KeyError as e:
print("Missing key:", e) # Missing key: 'age'
Logic errors: the most treacherous
This code gives no error, but it is wrong:
def is_adult(age):
return age > 18 # it should be >= 18!
print(is_adult(18)) # False (an 18-year-old would be a "minor")
It is only discovered by testing with the right cases, in this example the value 18. That is what the rest of the lesson is about.