Python exceptions are raised at runtime when something goes wrong — from passing the wrong argument type to failing to import a module. Every entry below includes a clear explanation of what triggers the error and the exact code fix.

Error Codes

ErrorDescriptionFix
AttributeErrorObject has no attribute — accessing a non-existent attribute or methodCheck the object type with type(), verify the attribute name, and handle None returns
FileNotFoundErrorNo such file or directory — the file path does not existUse os.path.exists() to check before opening, and verify the path string
ImportErrorModule not found or cannot import name — missing package or circular importInstall the package with pip install, check the module name, and resolve circular dependencies
IndentationErrorUnexpected indent or unindent — inconsistent whitespaceUse spaces consistently (PEP 8 recommends 4), and enable editor whitespace display
IndexErrorList index out of range — accessing beyond the list lengthCheck the list length with len(), use enumerate(), and handle empty lists
KeyErrorDictionary key not found — accessing a missing dictionary keyUse dict.get(key, default), check key in dict first, or use dict.setdefault()
SyntaxErrorInvalid syntax — code cannot be parsed before executionReview the line number, check for missing colons, brackets, or quotes
TypeErrorUnsupported operand type — operation applied to wrong typeConvert types explicitly, check isinstance(), and validate function arguments
ValueErrorInvalid argument — correct type but wrong valueValidate input before conversion, use try/except, and check boundary conditions
ZeroDivisionErrorDivision by zero — mathematical operation with zero divisorAdd input validation, check for zero before dividing, and use math.isclose() for floats

Quick Debug

# Show the full traceback in a script
import traceback
try:
    risky_operation()
except Exception as e:
    traceback.print_exc()