10 Most Common Python Errors and How to Fix Them
Python is beginner-friendly, but its error messages can still be confusing. Here are the 10 most common Python errors and how to fix them.
1. SyntaxError: invalid syntax
This is the most common Python error. It means your code has incorrect syntax: missing colons, unmatched parentheses, or incorrect indentation. Python points to the problematic line with a caret (^). Fix: check the line before the caret for missing operators, colons, or brackets.
2. NameError: name 'x' is not defined
You are trying to use a variable or function that has not been defined. Common causes: typos in variable names, using a variable before assignment, or forgetting to import a module. Fix: check spelling and ensure the variable is defined or imported.
3. TypeError: unsupported operand type
You are using an operator or function with incompatible types. Example: adding a string and an integer ("hello" + 5). Fix: convert types explicitly using str(), int(), or float() before the operation.
4. IndexError: list index out of range
You are accessing a list element at an index that does not exist. Lists are zero-indexed, so a list of 3 elements has indexes 0, 1, and 2. Fix: check list length with len() before accessing, or use try/except to handle the error.
5. KeyError: 'key'
You are accessing a dictionary key that does not exist. Fix: use dict.get(key) which returns None for missing keys, or use try/except KeyError. Check if the key exists with the in operator before access.
6. ValueError: invalid literal
You are passing an inappropriate value to a function. Example: int("hello") raises ValueError because "hello" is not a valid integer. Fix: validate inputs before conversion, or use try/except.
7. AttributeError: 'object' has no attribute 'x'
You are accessing an attribute or method that does not exist on the object. Common cause: typos or using the wrong type. Fix: check if the attribute exists with hasattr() or use dir() to list available attributes.
8. ImportError: No module named 'x'
Python cannot find the module you are trying to import. Fix: install the module with pip, check the module name spelling, and ensure the module is in your Python path. Use pip list to check installed packages.
9. IndentationError: unexpected indent
Python is strict about indentation. Mixing tabs and spaces causes this error. Fix: use 4 spaces consistently. Configure your editor to convert tabs to spaces. Never mix tabs and spaces.
10. ZeroDivisionError: division by zero
You are dividing a number by zero. Fix: check the divisor before division, or use try/except. Use a small epsilon like 1e-10 instead of zero in scientific calculations.