Reading Error Messages

Errors are normal

Every programmer sees errors every day. An error message isn't Python being angry – it's Python telling you what went wrong. Learning to read them is a superpower.

How to read one

When something goes wrong, Python prints a traceback. Read it from the bottom:

  • The last line says the type of error and a short explanation.
  • The lines above show where it happened, including the line number.

The errors you'll meet most

NameError – you used a name Python doesn't know. Usually a typo:

message = "hi"
print(mesage)

Output (Python stops with an error)

NameError: name 'mesage' is not defined

TypeError – you mixed types that don't work together:

print("Age: " + 21)

Output (Python stops with an error)

TypeError: can only concatenate str (not "int") to str

ValueError – the type is right, but the value isn't usable:

print(int("twenty"))

Output (Python stops with an error)

ValueError: invalid literal for int() with base 10: 'twenty'

ZeroDivisionError – dividing by zero:

print(10 / 0)

Output (Python stops with an error)

ZeroDivisionError: division by zero

IndexError – asking for a position that doesn't exist:

colours = ["red", "green"]
print(colours[5])

Output (Python stops with an error)

IndexError: list index out of range

KeyError – asking a dictionary for a key it doesn't have:

ages = {"asha": 21}
print(ages["ravi"])

Output (Python stops with an error)

KeyError: 'ravi'

SyntaxError and IndentationError – the code isn't written correctly, e.g. a missing colon, bracket or quote, or wrong indentation. Python finds these before running anything.

Tip: Copy the last line of an error into a search engine. Someone has almost certainly had the same problem.

HOME LEARN COMMUNITY DASHBOARD