}

Most Common Python Errors and How to Fix Them (2026)

Most Common Python Errors and How to Fix Them (2026)

Python is beginner-friendly, but its error messages can be cryptic at first. This guide catalogs every major category of Python error with a plain-English explanation and a pointer to the dedicated fix page. Each article has a direct solution at the top, before/after code, and FAQs.

Last updated: March 2026


How Python Error Types Work

Python distinguishes between errors that occur before your code runs and errors that occur while it runs.

Syntax errors and compile-time errors are caught when Python parses your file. Your program will not start at all:

  • SyntaxError — invalid Python syntax
  • IndentationError — wrong indentation (a subclass of SyntaxError)
  • TabError — mixed tabs and spaces (a subclass of IndentationError)

Runtime exceptions are raised while the program is running. Python generates a traceback that shows exactly which line caused the problem and which functions were on the call stack at the time:

Traceback (most recent call last):
  File "app.py", line 12, in <module>
    result = process(data)
  File "app.py", line 7, in process
    return data["key"]
TypeError: 'NoneType' object is not subscriptable

Reading the traceback from bottom to top is the fastest way to find the problem. The last line tells you the error type and message. The lines above show the call chain that led to it.


Category 1: Import and Module Errors

ModuleNotFoundError: No module named 'X'

The most common error for new Python developers. Python cannot find a package you are trying to import.

Most common causes: - The package is not installed (pip install packagename) - You are in the wrong virtual environment - The package name differs from the import name (e.g., pip install Pillow but import PIL) - Wrong Python version (pip vs pip3)

Quick fix:

pip install packagename
# or for Python 3 specifically
python3 -m pip install packagename

Full guide: Fix Python ModuleNotFoundError: No module named 'X'


ImportError: cannot import name 'X' from 'Y'

The module exists and is installed, but the specific name you are trying to import from it does not exist. Common causes: the name was renamed in a newer version, a typo in the imported name, or importing from the wrong submodule.

# BROKEN
from os.path import exists_file   # no such function

# CORRECT
from os.path import isfile

Category 2: Indentation Errors

IndentationError: unexpected indent / TabError: inconsistent use of tabs and spaces

Python uses indentation to define code blocks. Any inconsistency — an extra space, a tab where Python expects spaces, or mixed tabs and spaces — triggers this error.

Quick fix: Configure your editor to use 4 spaces per indent level and convert all tabs to spaces. Never mix the two.

# BROKEN — second line has unexpected indent
x = 1
    y = 2   # IndentationError

# CORRECT
x = 1
y = 2

Full guide: Fix Python IndentationError and TabError: Tabs vs Spaces


Category 3: Type Errors

TypeError: 'X' object is not subscriptable

You used square bracket notation (obj[key]) on an object that does not support it. Most often the object is None because a function returned nothing (implicitly return None).

# BROKEN — get_user() returns None when user not found
user = get_user(999)
name = user["name"]   # TypeError: 'NoneType' object is not subscriptable

# CORRECT
user = get_user(999)
if user is not None:
    name = user["name"]

Full guide: Fix Python TypeError: X object is not subscriptable


TypeError: unsupported operand type(s) for +: 'int' and 'str'

You tried to combine incompatible types. Python does not implicitly convert between int and str.

# BROKEN
age = 25
print("Age: " + age)   # TypeError

# CORRECT
print("Age: " + str(age))
# or
print(f"Age: {age}")

TypeError: X() takes Y positional arguments but Z were given

You called a function with the wrong number of arguments. If it is a method, you may have forgotten self in the class definition, or forgotten to pass a required argument.

class Dog:
    def bark(self):   # forgot self → bark() takes 0 args but 1 was given
        print("woof")

# or called with too many args:
def greet(name):
    return f"Hello, {name}"

greet("Alice", "Bob")   # takes 1, given 2

Category 4: Attribute Errors

AttributeError: 'X' object has no attribute 'Y'

You tried to access an attribute or method that does not exist on the object. The most common scenario is that a function returned None and you called a method on it without checking.

# BROKEN
result = some_function()
result.process()   # AttributeError: 'NoneType' object has no attribute 'process'

# CORRECT
result = some_function()
if result is not None:
    result.process()

Full guide: Fix Python AttributeError: 'X' object has no attribute 'Y'


Category 5: Name Errors

NameError: name 'X' is not defined

Python cannot find a variable or function name in the current scope. Common causes: typo, variable used before assignment, variable defined inside an if block that did not execute, or forgetting to import a module.

# BROKEN — typo
pritn("hello")   # NameError: name 'pritn' is not defined

# BROKEN — used before assignment
print(count)
count = 0

# CORRECT
count = 0
print(count)

UnboundLocalError: local variable 'X' referenced before assignment

A variable is assigned somewhere inside a function, which makes Python treat it as local throughout the function — even before the assignment line.

count = 0

def increment():
    count += 1   # UnboundLocalError: count referenced before assignment
    # Python sees 'count =' below and treats count as local

Fix: use global count (or nonlocal count for closures) if you intend to modify the outer variable.


Category 6: Value Errors

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

You passed a string to int() that cannot be parsed as a number.

# BROKEN
n = int("3.14")   # ValueError — use float() first, or round

# CORRECT
n = int(float("3.14"))  # 3

ValueError: not enough values to unpack

You are trying to unpack a sequence into more variables than it contains.

a, b, c = [1, 2]   # ValueError: not enough values to unpack (expected 3, got 2)

Category 7: Index and Key Errors

IndexError: list index out of range

You accessed a list (or tuple) at an index that does not exist.

items = [1, 2, 3]
print(items[5])   # IndexError: list index out of range

# Safe access
print(items[5] if 5 < len(items) else None)

KeyError: 'X'

You tried to look up a key in a dictionary that is not present.

d = {"a": 1}
print(d["b"])   # KeyError: 'b'

# Safe alternatives
print(d.get("b"))          # None
print(d.get("b", 0))       # 0 (default)
print(d.get("b", "N/A"))   # "N/A"

Category 8: Runtime and Recursion Errors

RecursionError: maximum recursion depth exceeded

Your recursive function does not have a base case, or the input is too deep for Python's default stack limit (1000 frames).

import sys
sys.setrecursionlimit(5000)   # increase if needed, but first check your base case

ZeroDivisionError: division by zero

# CORRECT pattern
denominator = get_value()
result = numerator / denominator if denominator != 0 else 0

Category 9: File and OS Errors

FileNotFoundError: [Errno 2] No such file or directory: 'X'

The path you passed to open() or another file function does not exist, or your working directory is not what you expect.

import os
print(os.getcwd())   # debug: check where Python is looking

# Use absolute paths or __file__-relative paths
import pathlib
here = pathlib.Path(__file__).parent
config = here / "config.json"

Debugging Any Python Error: A Checklist

  1. Read the full traceback — the bottom line tells you the error type and message; work upward to find your code.
  2. Check the line number — look at the line Python points to and the line just before it.
  3. Print or inspect the value — use print(type(x), x) to see what you actually have vs. what you expected.
  4. Check for None — most AttributeError and TypeError: not subscriptable errors come from a value being None.
  5. Verify your environment — confirm you are in the right virtualenv and using the right Python version.
  6. Isolate the problem — paste the minimal failing code into a REPL to reproduce it outside your application.

All Python Error Fix Pages

Error Article
ModuleNotFoundError: No module named 'X' Fix ModuleNotFoundError
IndentationError / TabError Fix IndentationError and TabError
TypeError: 'X' object is not subscriptable Fix TypeError not subscriptable
AttributeError: 'X' object has no attribute 'Y' Fix AttributeError

Related Pages