Skip to content
Happy Programming Guide
Start learning
Debugging & Errors

Common Python Errors and How to Fix Them

The Python errors beginners hit most: SyntaxError, IndentationError, NameError, TypeError, ValueError, IndexError, KeyError and ModuleNotFoundError — each with a cause and a fix.

Python’s error messages are unusually good. Once you recognise the eight below, most of your first months of debugging becomes routine.

SyntaxError#

Output
SyntaxError: expected ':'

Python could not even parse your file. Usually one of:

  • A missing colon after if, for, while, def or class
  • An unclosed bracket or quote
  • = where you meant ==
Python
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#

Output
IndentationError: expected an indented block

Python 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#

Output
NameError: name 'totl' is not defined

You 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#

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

You did something to a value its type does not support. Nearly always a number-versus-text mix-up:

Python
age = input("Age: ")     # text, always
print("Next year: " + age + 1)      # TypeError

print(f"Next year: {int(age) + 1}") # fixed

Another common form is 'NoneType' object is not subscriptable, which means a function returned nothing and you tried to index the result.

ValueError#

Output
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:

Python
raw = input("Enter a number: ")

try:
    number = int(raw)
except ValueError:
    print("That was not a whole number.")

IndexError#

Output
IndexError: list index out of range

You asked for a position that does not exist. Remember the last item is at len(items) - 1.

Python
items = ["a", "b", "c"]
print(items[3])      # IndexError
print(items[-1])     # "c" — last item
if items:
    print(items[0])  # guard against an empty list

KeyError#

Output
KeyError: 'email'

You asked a dictionary for a key it does not have. Use get() when the key is genuinely optional:

Python
print(person.get("email", "not provided"))

See Python dictionaries explained.

ModuleNotFoundError#

Output
ModuleNotFoundError: No module named 'requests'

The package is not installed for the Python you are running.

Terminal
python -m pip install requests

Using 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#

Output
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#

Python
average = total / len(items)     # crashes when items is empty

average = total / len(items) if items else 0    # fixed

Questions 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#

Next lessonHow to read a stack trace

Keep reading

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *