Back to Home

Python Errors

Complete guide to Python exceptions, error types, and how to fix them.

15 Exception Types
NameError
Name is not defined

Occurs when trying to access a variable or function that hasn't been defined.

print(x) # NameError: name 'x' is not defined
TypeError
Unsupported operand type

Occurs when performing an operation on incompatible data types.

'5' + 3 # TypeError: can only concatenate str (not "int") to str
SyntaxError
Invalid syntax

Occurs when Python parser encounters invalid syntax.

if True # SyntaxError: expected ':'
IndentationError
Unexpected indent

Occurs when indentation is incorrect or inconsistent.

if True: print('yes') print('no') # IndentationError
AttributeError
Object has no attribute

Occurs when trying to access an attribute or method that doesn't exist on an object.

x = 5; x.append(1) # AttributeError: 'int' object has no attribute 'append'
KeyError
Key not found

Occurs when trying to access a dictionary key that doesn't exist.

d = {}; print(d['key']) # KeyError: 'key'
ValueError
Invalid value

Occurs when a function receives the correct type but an inappropriate value.

int('abc') # ValueError: invalid literal for int() with base 10: 'abc'
IndexError
List index out of range

Occurs when trying to access an index that doesn't exist in a list or tuple.

lst = [1, 2]; print(lst[5]) # IndexError: list index out of range
ImportError
Cannot import module

Occurs when trying to import a module that cannot be found or loaded.

import non_existent # ImportError: No module named 'non_existent'
ZeroDivisionError
Division by zero

Occurs when trying to divide a number by zero.

5 / 0 # ZeroDivisionError: division by zero
FileNotFoundError
No such file or directory

Occurs when trying to open a file that doesn't exist.

open('non_existent.txt') # FileNotFoundError: [Errno 2] No such file or directory
ModuleNotFoundError
No module named

Occurs when trying to import a module that is not installed or not found.

import requests # ModuleNotFoundError: No module named 'requests'
PermissionError
Permission denied

Occurs when trying to access a file or directory without proper permissions.

open('/root/file.txt') # PermissionError: [Errno 13] Permission denied
OSError
Operating system error

A general operating system error occurred, such as file system or network issues.

open('file.txt', 'r') # OSError: [Errno 2] No such file or directory: 'file.txt'
RuntimeError
Runtime error

A generic runtime error occurred that doesn't fit into other specific error categories.

raise RuntimeError('Custom error message') # RuntimeError: Custom error message