Python error types
Click any bar to see a code example and what Python does.
CodeOutput
Click a bar to expand
Syntax error — Python can't even read this
def get_density(city_data)
return city_data["pop"] / city_data["area"]
File "example.py", line 1
def get_density(city_data)
^
SyntaxError: expected ':'
The missing colon stops Python during the syntax check. Nothing in the file runs, not even earlier lines that were perfectly fine.
Runtime error. Python understood the code, but something broke while running
population = 120000
area_km2 = 78.6
density = population / area_km
print(f"Density: {density:.1f}")
Traceback (most recent call last):
File "example.py", line 4, in <module>
density = population / area_km
NameError: name 'area_km' is not defined
Lines 1 and 2 ran fine. The crash happened at line 4: a typo in the variable name. Python tells you exactly where it stopped.
Common types: NameError, TypeError, KeyError, IndexError, AttributeError
Semantic error — Python did exactly what you said, not what you meant
temps_f = [32, 68, 104]
temps_c = [(t - 32) / 1.8 for t in temps_f]
print(temps_c)
[0.0, 20.0, 40.0]
No error. But the formula should be (t - 32) * 5/9
The result looks plausible, that's what makes this the hardest to catch.
The code runs from start to finish. No traceback, no warning. You only know something is wrong if you check the output carefully.
Reading a traceback
A traceback is read bottom to top — start at the error, then follow the call chain upward.
Traceback (most recent call last):
File "example.py", line 9, in <module>
summarize(berkeley)
File "example.py", line 5, in summarize
density = get_density(city_data)
File "example.py", line 2, in get_density
return city_data["area"]
~~~~~~
KeyError: 'area'
^ start here
function name
which function was running
line number
where in the file
function name
called by <module>
error type
'area' key doesn't exist