Skip to content

Python Error Fixes -- How to Fix Common Python Errors

DodaTech Updated 2026-06-22 5 min read

Python errors like IndentationError and ImportError halt your script immediately -- this guide shows you how to diagnose and fix the most common Python errors with exact traceback analysis and tested solutions.

What You'll Learn

Why It Matters

Python errors waste hours for beginners and seasoned developers alike. Knowing the exact fix for each error type lets you resolve issues in seconds instead of searching forums.

Real-World Use

When your Django app throws a KeyError or your data science script hits a TypeError, reading the traceback correctly and applying the matching fix keeps your project on schedule.

Common Python Errors Table

Error Message Cause Fix
IndentationError: unexpected indent Mixing tabs and spaces or wrong block level Use 4 spaces consistently across the file
ImportError: No module named xyz Module not installed or not in PYTHONPATH Install with pip install xyz or check sys.path
TypeError: unsupported operand type(s) Using wrong types in an operation Convert types with int(), str(), float() before operation
KeyError: 'key_name' Accessing a dict key that does not exist Use .get() with a default value or check with in
ValueError: invalid literal for int() Converting string to int with non-numeric content Wrap in try-catch or validate input with .isdigit()
AttributeError: NoneType object has no attribute Calling a method on a None return value Check the return value is not None before calling methods
FileNotFoundError: No such file or directory File path is incorrect Use os.path.exists() to verify path before opening

Step-by-Step Fixes

Fix 1: Python IndentationError

# bad.py
def greet():
print("Hello")  # IndentationError: expected an indented block
# fixed.py
def greet():
    print("Hello")  # 4 spaces before print

greet()

Expected output:

Hello

Fix 2: ImportError -- Module Not Found

# bad.py
import requests

response = requests.get("https://api.example.com")
# ImportError: No module named requests
# fixed.py
# First run: pip install requests in the terminal

import requests

response = requests.get("https://api.example.com")
print(response.status_code)

Expected output:

200

Fix 3: KeyError -- Missing Dictionary Key

# bad.py
user = {"name": "Alice", "age": 30}
print(user["email"])  # KeyError: 'email'
# fixed.py
user = {"name": "Alice", "age": 30}
email = user.get("email", "No email provided")
print(email)  # No email provided

Expected output:

No email provided

Fix 4: TypeError -- Unsupported Operand Type

# bad.py
age = 30
message = "You are " + age + " years old"
# TypeError: can only concatenate str (not "int") to str
# fixed.py
age = 30
message = "You are " + str(age) + " years old"
print(message)  # You are 30 years old

Expected output:

You are 30 years old

Fix 5: ValueError -- Invalid Literal for Int

# bad.py
user_input = "abc"
number = int(user_input)  # ValueError: invalid literal for int()
# fixed.py
user_input = "abc"
try:
    number = int(user_input)
except ValueError:
    number = 0
    print("Invalid input, using 0 as default")

print(number)  # 0

Expected output:

Invalid input, using 0 as default
0

Fix 6: AttributeError on None

# bad.py
def find_user(user_id):
    if user_id != 42:
        return None
    return {"name": "Alice"}

user = find_user(99)
print(user["name"])  # TypeError: 'NoneType' object is not subscriptable
# fixed.py
def find_user(user_id):
    if user_id != 42:
        return None
    return {"name": "Alice"}

user = find_user(99)
if user is not None:
    print(user["name"])
else:
    print("User not found")

Expected output:

User not found

Python Error Diagnosis Flowchart

flowchart TD
    A[Python Error Detected] --> B{Error Type?}
    B -->|IndentationError| C[Check tabs vs spaces]
    C --> D[Use 4 spaces consistently]
    B -->|ImportError| E[Check installed packages]
    E --> F[Install module with pip]
    B -->|KeyError| G[Check dictionary keys]
    G --> H[Use .get with default value]
    B -->|TypeError| I[Check operand types]
    I --> J[Convert types explicitly]
    B -->|ValueError| K[Validate input format]
    K --> L[Use try-catch or isdigit]
    B -->|AttributeError| M[Check for None returns]
    M --> N[Guard with None check]
    D --> O[Error Resolved]
    F --> O
    H --> O
    J --> O
    L --> O
    N --> O

Prevention Tips

  • Configure your editor to convert tabs to spaces and set indent to 4 spaces
  • Use a virtual environment and maintain a requirements.txt file for all dependencies
  • Prefer dictionary .get() method over direct key access when keys may not exist
  • Use type hints to catch type mismatches early with tools like mypy
  • Validate user input before conversion with str.isdigit() or try-catch blocks
  • Always check function return values for None before accessing attributes
  • Use pathlib.Path for file operations to avoid cross-platform path issues

Practice Questions

  1. What causes an IndentationError in Python? Answer: Mixing tabs and spaces, or inconsistent indentation levels. Python requires consistent indentation (4 spaces preferred) for block structures.

  2. How do you fix an ImportError for a missing module? Answer: Install the module with pip install <module-name>. If already installed, check the Python environment and PYTHONPATH.

  3. What is the difference between KeyError and IndexError? Answer: KeyError occurs when accessing a missing dictionary key. IndexError occurs when accessing a list or tuple index that is out of range.

  4. How do you safely convert a string to an integer in Python? Answer: Use str.isdigit() to check first, or wrap int() in a try-catch ValueError handler for invalid input.

  5. Challenge: Write a function that reads a JSON file, safely handles FileNotFoundError, JSONDecodeError, and KeyError, and returns a default dictionary with all errors explained. Answer:

    import json
    from pathlib import Path
    
    def safe_read_json(filepath):
        default = {"error": "unknown", "data": {}}
        try:
            data = json.loads(Path(filepath).read_text())
            return {"error": None, "data": data}
        except FileNotFoundError:
            return {"error": "File not found", "data": default}
        except json.JSONDecodeError as e:
            return {"error": f"Invalid JSON: {e}", "data": default}
        except KeyError as e:
            return {"error": f"Missing key: {e}", "data": default}
    

Quick Reference

Error Cause Quick Fix
IndentationError Mixed tabs and spaces Re-indent with 4 spaces
ImportError Module not installed pip install <module>
KeyError Missing dictionary key Use .get(key, default)
TypeError Wrong operand type str(), int(), float() to cast
ValueError Invalid string for conversion Validate with .isdigit() or try-catch
AttributeError Method on None object Check value is not None first
FileNotFoundError Wrong file path Use pathlib.Path and exists()

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro