Common Python Errors and Solutions¶
When Python encounters a situation it cannot execute, it terminates the script and prints a Traceback. Understanding how to interpret tracebacks makes debugging straightforward.
How to Read a Python Traceback¶
A Python traceback should be read from the bottom to the top:
Traceback (most recent call last):
File "calculator.py", line 18, in <module>
result = compute(user_input)
File "calculator.py", line 8, in compute
return 100 / value
ZeroDivisionError: division by zero
- Bottom line: States the exact exception type (
ZeroDivisionError) and the descriptive error message (division by zero). - Line above the bottom: Indicates the exact file name (
calculator.py) and line number (line 8) where the exception occurred.
1. SyntaxError: Invalid Syntax¶
Cause¶
Python encountered code that violates language grammar rules before execution began.
2. IndentationError: Expected an Indented Block¶
Cause¶
Python expects an indented block after statements ending in a colon (:) such as def, if, for, while, or class.
3. NameError: Name is Not Defined¶
Cause¶
A variable or function is referenced that has not been defined in the current scope, or its name was misspelled.
4. TypeError: Incompatible Types or Arguments¶
Cause¶
An operation or function was applied to an object of an inappropriate type.
5. IndexError: List Index Out of Range¶
Cause¶
An index position was requested that is greater than or equal to the length of the sequence.
6. KeyError: Key Not Found¶
Cause¶
A dictionary key was accessed using square brackets dict[key] that does not exist.
7. AttributeError: Object Has No Attribute¶
Cause¶
A method or attribute was accessed that does not exist on that data type.