Common Python Errors - Definitions & Examples
SyntaxError
Occurs when Python cannot parse code due to incorrect syntax.
Example:
if True print('Hello')
# SyntaxError: invalid syntax
IndentationError
Occurs when code blocks are not properly indented.
Example:
def greet():
print('Hi')
# IndentationError: expected an indented block
NameError
Occurs when a variable or function name is not defined.
Example:
print(age)
# NameError: name 'age' is not defined
TypeError
Occurs when an operation is applied to an object of inappropriate type.
Example:
'2' + 2
# TypeError: can only concatenate str (not "int") to str
Common Python Errors - Definitions & Examples
ValueError
Occurs when a function receives an argument of right type but inappropriate value.
Example:
int('abc')
# ValueError: invalid literal for int() with base 10: 'abc'
IndexError
Occurs when accessing a list index that is out of range.
Example:
lst = [1,2,3]; print(lst[5])
# IndexError: list index out of range
KeyError
Occurs when accessing a dictionary with a key that doesn't exist.
Example:
d = {'name':'John'}; print(d['age'])
# KeyError: 'age'
AttributeError
Occurs when an attribute reference or assignment fails.
Example:
'hello'.push('o')
# AttributeError: 'str' object has no attribute 'push'
ModuleNotFoundError
Common Python Errors - Definitions & Examples
Occurs when trying to import a non-existent module.
Example:
import notamodule
# ModuleNotFoundError: No module named 'notamodule'
ImportError
Occurs when importing a part of a module that doesn't exist.
Example:
from math import cosine
# ImportError: cannot import name 'cosine' from 'math'
ZeroDivisionError
Occurs when dividing a number by zero.
Example:
5/0
# ZeroDivisionError: division by zero
OverflowError
Occurs when a number is too large to be represented.
Example:
import math; math.exp(1000)
# OverflowError: math range error
FileNotFoundError
Occurs when trying to open a file that doesn't exist.
Common Python Errors - Definitions & Examples
Example:
open('nofile.txt')
# FileNotFoundError: [Errno 2] No such file or directory
RuntimeError
A generic error raised when an error is detected that doesn't fall in other categories.
Example:
raise RuntimeError('Unexpected error')
AssertionError
Occurs when an assert statement fails.
Example:
assert 2 + 2 == 5
# AssertionError