Python’s error messages are unusually good. Once you recognise the eight below, most of your first months of debugging becomes routine.
SyntaxError#
SyntaxError: expected ':'Python could not even parse your file. Usually one of:
- A missing colon after
if,for,while,deforclass - An unclosed bracket or quote
=where you meant==
if age > 18 # missing colon
print("adult")
if age > 18: # fixed
print("adult")If the reported line looks fine, check the line above. An unclosed bracket is reported one line late.
IndentationError / TabError#
IndentationError: expected an indented blockPython uses indentation to decide what belongs inside a block. Every if, for and def needs an indented line under it.
TabError means you mixed tabs and spaces. Set your editor to insert spaces for tabs and the problem disappears permanently.
NameError#
NameError: name 'totl' is not definedYou used a name Python has never seen. Three causes, in order of likelihood:
- A typo — Python is showing you the exact misspelling
- You used it before the line that creates it
- It was created inside a function and you are using it outside
TypeError#
TypeError: can only concatenate str (not "int") to strYou did something to a value its type does not support. Nearly always a number-versus-text mix-up:
age = input("Age: ") # text, always
print("Next year: " + age + 1) # TypeError
print(f"Next year: {int(age) + 1}") # fixedAnother common form is 'NoneType' object is not subscriptable, which means a function returned nothing and you tried to index the result.
ValueError#
ValueError: invalid literal for int() with base 10: 'hello'The type was right but the value was not — int() was given something that is not a number. Guard the conversion:
raw = input("Enter a number: ")
try:
number = int(raw)
except ValueError:
print("That was not a whole number.")IndexError#
IndexError: list index out of rangeYou asked for a position that does not exist. Remember the last item is at len(items) - 1.
items = ["a", "b", "c"]
print(items[3]) # IndexError
print(items[-1]) # "c" — last item
if items:
print(items[0]) # guard against an empty listKeyError#
KeyError: 'email'You asked a dictionary for a key it does not have. Use get() when the key is genuinely optional:
print(person.get("email", "not provided"))See Python dictionaries explained.
ModuleNotFoundError#
ModuleNotFoundError: No module named 'requests'The package is not installed for the Python you are running.
python -m pip install requestsUsing python -m pip rather than plain pip guarantees it installs for the same interpreter that will run your code. If you use a virtual environment, activate it first.
AttributeError#
AttributeError: 'list' object has no attribute 'lower'You called a method that exists on a different type. lower() belongs to strings, not lists. Print type(value) just above the failing line and the mismatch is usually obvious.
ZeroDivisionError#
average = total / len(items) # crashes when items is empty
average = total / len(items) if items else 0 # fixedQuestions people ask#
What is a traceback?
The list of function calls that led to the error, oldest first. The last entry is where it actually failed. See how to read a stack trace.
Should I wrap everything in try/except?
No. Catch specific errors you expect and can handle. A bare except: swallows genuine bugs and makes them far harder to find.
Why does my code work in one folder but not another?
File paths are usually relative to where you ran the command, not where the script lives. Print os.getcwd() to see what Python thinks the current folder is.
Where to go next#
- How to read a stack trace
- Python data types explained — prevents most TypeErrors
- Why is my Python code not working? — start here if you are not sure which error you have
- Python try / except explained — handling errors instead of crashing