01 The shape of a traceback
Python prints the route it took to the error, oldest call first. Beginners read it top to bottom and get lost in library files. Read it the other way.
- Last line — the error type and message. This is what went wrong.
- Line above it — the code that failed. This is where.
- Everything else — how the program got there. Usually ignorable.
If the last line names a file you did not write, keep scanning upward for the last line that is your file. That is where your bug is.
a traceback, read from the bottom
Traceback (most recent call last):
File "plants.py", line 12, in <module>
main()
File "plants.py", line 8, in main
print(total_days(plants))
File "plants.py", line 4, in total_days
total = total + plant["days"]
KeyError: 'days' <- WHAT: no key called "days"
WHERE: plants.py line 4
02 SyntaxError
Python could not even read your file. Nothing ran at all — which is why adding a print to investigate changes nothing.
The reported line number is where Python noticed, not always where the mistake is. An unclosed bracket is reported on the line after it. Always check the line above the one named.
the usual causes
print("hello" # unclosed bracket -> error reported on the NEXT line
if age > 18 # missing colon
print("adult")
if age = 18: # = instead of ==
print("exactly")
print("it's here") # a quote ending the string early
# IndentationError is a SyntaxError in a hat
def greet():
print("hi") # body not indented
03 NameError
You used a name Python has never seen. Four causes, and the first is by far the most common.
Python is case-sensitive, so Print, TRUE and myVar are all different from print, True and myvar.
NameError
pritn("hello") # NameError: name 'pritn' is not defined
print(total) # used before it was assigned
total = 5
if False:
x = 1
print(x) # the branch never ran, so x never existed
def count():
n = 5
count()
print(n) # n only exists inside the function
04 TypeError
The right names, the wrong kinds of thing. Nearly always a string where a number belongs, and nearly always traceable to input().
TypeError
age = input("Age? ") # ALWAYS a string
print(age + 1) # TypeError: can only concatenate str to str
print(int(age) + 1) # fixed
len(42) # TypeError: object of type 'int' has no len()
def greet(name):
print(name)
greet() # TypeError: missing 1 required positional argument
greet("a", "b") # TypeError: takes 1 positional argument but 2 were given
total = None
total + 1 # TypeError: unsupported operand type(s) for +
05 IndexError and KeyError
Asking a collection for something that is not in it. IndexError is for lists and positions, KeyError is for dictionaries and names.
A list of 3 items has positions 0, 1 and 2. There is no position 3. len(items) is always one past the last valid index.
IndexError / KeyError
plants = ["fern", "cactus", "ivy"]
plants[3] # IndexError: list index out of range
plants[-1] # "ivy" - negative counts from the end, this is fine
# The off-by-one in a loop
for i in range(len(plants)):
print(plants[i + 1]) # IndexError on the last pass
plant = {"name": "fern", "room": "kitchen"}
plant["days"] # KeyError: 'days'
plant.get("days") # None instead of an error
plant.get("days", 7) # 7 as a fallback
06 ValueError
The right type, a value it cannot work with. The classic is int() on text that is not a number.
This one matters because it is the error a user can cause by typing something unexpected, so it is the one worth catching.
ValueError
int("abc") # ValueError: invalid literal for int() with base 10
int("") # same - an empty input box
int("3.9") # ValueError - int() will not parse a decimal string
float("3.9") # 3.9 - this is fine
# Catch it where a user is involved
while True:
try:
age = int(input("Age? "))
break
except ValueError:
print("Please type a whole number.")
07 When there is no error at all
A program that runs and gives the wrong answer is harder than one that crashes, because nothing points at the line.
Three cheap techniques, in the order to try them.
08 try and except
Catch an error only where you can do something sensible about it. Wrapping your whole program in try hides bugs instead of fixing them.
Never write a bare except:. It swallows every error including the typos in your own code, and you lose the message that would have told you what was wrong. Always name the error you expect.
try_except.py
try:
age = int(input("Age? "))
except ValueError:
print("That is not a number.")
age = 0
# Several, handled differently
try:
value = plant["days"]
except KeyError:
value = 7
# Bad: hides everything, including your own typos
try:
do_everything()
except:
pass
09 Error messages at a glance
One table for when you recognise the name but not the cause.
10 Asking for help well
A good question gets an answer in two minutes. A bad one costs both of us ten.
Bring four things, every time:
- The full error message, copied as text — not a photo of the screen.
- The line it names, and the few lines around it.
- What you expected to happen.
- What you already tried.
Writing that out solves the problem by itself often enough that it is worth doing before you ask anyone.
the difference
Not useful: “my code does not work”
Useful: “Line 8 raises TypeError: can only concatenate str to str. I expected it to add the ages. I checked and age is a string from input(), but wrapping it in int() gave a ValueError instead.”
Nothing on this page mentions that. Try a shorter word, or clear the filter.