Jan 3rd, ‘25/15 min read

Types of Errors in Python and How to Fix Them

Learn how to identify and fix common Python errors like SyntaxError, TypeError, and NameError with this quick guide!

Types of Errors in Python and How to Fix Them

Python, a language celebrated for its simplicity and readability, is not without its challenges, especially when it comes to debugging.

Whether you’re a seasoned developer or a beginner, understanding the types of errors you can encounter in Python is crucial for smooth coding.

In this blog, we will explore the various types of errors in Python, their causes, and how to handle them effectively.

What Are Errors in Python?

In programming, errors are events that disrupt the normal flow of execution. Python errors can manifest in different ways, depending on the type of issue and when it occurs during program execution. Errors are broadly categorized into three types:

  • Syntax Errors
  • Runtime Errors
  • Logical Errors

Each of these errors has its own set of characteristics and troubleshooting methods. Let’s break them down in more detail.

🤝
For more on effective logging in Python, check out our guide on Python Logging with Structlog.

Types of Errors in Python Cheatsheet

Error TypeDescriptionCommon CausesHow to Fix
SyntaxErrorOccurs when Python encounters incorrect syntax.Missing punctuation, extra commas, incorrect function calls, etc.Check for missing or extra symbols like commas, parentheses, etc.
TypeErrorRaised when an operation or function is applied to an object of inappropriate type.Using incorrect data types for operations, like adding a string to an integer.Ensure correct data types and convert them if necessary.
IndexErrorOccurs when accessing an element in a list, tuple, or string with an invalid index.Index is out of the valid range of a list or tuple.Check if the index is within the valid range.
KeyErrorRaised when a dictionary key is not found in the dictionary.Attempting to access a non-existent key in a dictionary.Ensure the key exists before accessing or use .get() method.
AttributeErrorRaised when an invalid attribute reference is made on an object.Calling a method or accessing an attribute that doesn’t exist.Verify the object has the attribute and check for typos.
FileNotFoundErrorOccurs when trying to open a file that doesn’t exist.Trying to open a file that doesn’t exist in the specified path.Ensure the file exists or provide the correct path.
IndentationErrorOccurs when there’s an unexpected indentation in the code.Mixing tabs and spaces or incorrect indentation levels.Use consistent spaces (4 spaces per indentation) and avoid mixing tabs.
NameErrorRaised when a local or global name is not found.Using an undefined variable, misspelling a variable name, or improper imports.Define the variable or function, check for typos, and import modules properly.
ValueErrorRaised when a function receives an argument of the correct type but inappropriate value.Incorrect values for built-in functions (e.g., passing a negative number to sqrt()).Ensure the value fits the expected range or constraints.
ZeroDivisionErrorRaised when dividing by zero.Attempting to divide by zero.Check that the denominator is not zero before performing the division.
OverflowErrorOccurs when a calculation exceeds the limits of a data type.Performing arithmetic that exceeds the range of a number type (e.g., large int).Use larger data types or split large operations into smaller parts.

Syntax Errors: The Code Typos

What Are Syntax Errors?

A syntax error happens when the Python interpreter encounters a line of code that doesn’t follow the correct syntax rules of the language.

It’s like trying to speak a sentence in a language where the words are all jumbled up. The interpreter cannot understand the instructions, and thus, it raises an error.

Common Causes

  • Missing colons (:) after control structures like if, for, or while.
  • Mismatched parentheses, brackets, or braces.
  • Incorrect indentation (Python is very particular about indentation).
  • Typographical errors in keywords or variable names.

Example

if x > 5 print("x is greater than 5")

This code will throw a SyntaxError because it’s missing a colon after the if statement. The correct code should be:

if x > 5: 
    print("x is greater than 5")

How to Handle It?

  • Carefully check the structure of your code, paying special attention to punctuation and indentation.
  • Use an Integrated Development Environment (IDE) with syntax highlighting to spot mistakes early.
📖
For additional insights on logging best practices in Python, explore our article on Python Logging Best Practices.

Runtime Errors: Oops, Something Went Wrong During Execution

What Are Runtime Errors?

Runtime errors occur while your program is running. These errors are typically caused by invalid operations or other unexpected conditions that arise as the program executes. They can crash your program if not handled properly.

Common Causes

  • Division by zero
  • Accessing an undefined variable
  • Calling a method on an object that does not exist
  • File I/O errors

Example

a = 10
b = 0
result = a / b

In this example, dividing by zero will raise a ZeroDivisionError during runtime, leading to a program crash.

How to Handle It?

  • Use try-except blocks to catch errors and handle them gracefully without crashing the program.
  • Validate inputs to ensure operations like division don’t result in illegal values (e.g., zero).

Example:

try: 
    result = a / b 
except ZeroDivisionError: 
    print("Cannot divide by zero!")

Logical Errors: The Sneaky Culprits

What Are Logical Errors?

Unlike syntax and runtime errors, logical errors don’t necessarily prevent the program from running. However, they cause the program to produce incorrect results.

These errors are often harder to catch because they don't stop the program from running—they just make the output wrong.

Common Causes

  • Using incorrect algorithms or formulas
  • Mishandling variable values or logic
  • Mistakes in conditional statements or loops

Example

x = 10
y = 5
result = x - y * 2

The intention might have been to add x and y and then multiply by 2, but due to the order of operations, the result might be different from what was expected.

How to Handle It?

  • Review the logic thoroughly, focusing on the desired outcomes and whether your code matches them.
  • Write tests and debug iteratively to catch logical mistakes early in the development process.

Exceptions in Python: Handling Errors Gracefully

Sometimes, errors are not easily predictable, and that's where exceptions come in. Python provides a robust mechanism for handling runtime errors via exceptions. An exception is a special object that signals an error condition during the program’s execution.

Common Types of Exceptions

  • ValueError: Raised when a function receives an argument of the correct type but an inappropriate value.
  • TypeError: Raised when an operation or function is applied to an object of inappropriate type.
  • IndexError: Raised when trying to access an index that is out of range in a list or tuple.
  • KeyError: Raised when trying to access a key in a dictionary that doesn’t exist.

Example of Handling Exceptions

try:
    number = int(input("Enter a number: "))
except ValueError:
    print("That's not a valid number!")

In this example, if the user inputs anything other than a valid integer, a ValueError will be raised, and the program will handle it gracefully without crashing.

📝
For a deeper dive into OTLP headers and the OpenTelemetry Python SDK, check out our article on Whitespace in OTLP Headers and OpenTelemetry Python SDK.

Handling Errors with Assertions

An assertion is a sanity check to test whether a condition is true. If the condition is false, the program raises an AssertionError.

Example

x = 5
assert x > 0, "x should be greater than 0"

If x were less than or equal to zero, the program would raise an AssertionError and stop.

How to Fix Errors in Python?

Here are some quick tips to deal with errors:

  • Read error messages carefully: Python error messages are usually descriptive and will often tell you what went wrong and where.
  • Use debugging tools: Python has a built-in debugger, pdb, which helps in stepping through code line by line to find where things are going wrong.
  • Write tests: Unit tests, integration tests, and system tests can help catch errors early in development.
  • Check the documentation: If you're unsure about a function or method, check the Python documentation or consult online resources.

AttributeError: The Missing Attribute Mystery

What is an AttributeError?

An AttributeError occurs when you try to access or call an attribute (like a method or a variable) on an object that doesn’t possess that attribute.

It’s one of those errors that can leave you scratching your head, wondering, “Why isn’t this object behaving like I expect?”

Python objects are made up of attributes—variables or methods tied to the object. If you try to access an attribute that doesn’t exist, Python raises an AttributeError.

Common Causes of AttributeError

  • Typo in the attribute name: Misspelling a method or variable name can result in an AttributeError.
  • Accessing attributes from non-initialized or None objects: Trying to access attributes from None or an uninitialized object will raise this error.
  • Trying to access attributes of the wrong type of object: If you're working with a variable that isn't the object type you expect, trying to call a method or access an attribute that isn't defined on it will trigger an AttributeError.
  • Incorrect object initialization: When an object is not initialized properly, it might miss some expected attributes.

Example 1: Misspelled Attribute Name

class Car:
    def __init__(self, make, model):
        self.make = make
        self.model = model

my_car = Car("Toyota", "Corolla")
print(my_car.mak)  # Misspelled 'make'

In this case, the code raises an AttributeError because mak is a typo, and my_car doesn’t have an attribute by that name. The correct attribute name is make.

How to Handle It?

  • Double-check attribute names, ensuring there are no typos.
  • Use Python’s built-in dir() function to list all attributes of an object.
print(dir(my_car))  # List all attributes of 'my_car'

This can help you verify if an attribute exists or not.

Example 2: Accessing Attributes from None

car = None
print(car.make)  # Raises AttributeError

Here, trying to access the make attribute of None will raise an AttributeError because None does not have any attributes.

How to Handle It?

Always check if an object is initialized before accessing its attributes. You can do this with an if statement or try-except block:

if car is not None:
    print(car.make)
else:
    print("Car object is not initialized.")

Example 3: Accessing an Attribute from the Wrong Object Type

my_list = [1, 2, 3]
print(my_list.upper())  # Lists don’t have an 'upper' method

In this case, calling upper() on a list will raise an AttributeError because lists don’t have an upper() method (it's a method for strings).

How to Handle It?

  • Ensure you are calling methods or accessing attributes appropriate for the object’s type. Use type() to check the object type:
print(type(my_list))  # <class 'list'>
📝
To explore how to use a Golang package in Python, check out our guide on Using Golang Package in Python with gopy.

Preventing AttributeErrors

To prevent these types of errors:

1. Use Defensive Programming

Always check if attributes exist before accessing them, especially when working with external libraries or data sources.

2. Use Python’s getattr()

getattr() allows you to access an attribute of an object without throwing an error if it doesn’t exist.

getattr(my_car, 'make', 'Unknown')  # Returns 'Unknown' if 'make' doesn’t exist

3. Type Checking

If you're working with dynamic data, you might want to ensure that the object you're working with is the right type before accessing its attributes.

if isinstance(my_car, Car):
    print(my_car.make)

File and Module Errors: The Trouble with Files and Imports

1. FileNotFoundError: When the File is MIA

The FileNotFoundError is one of the most common file-related errors in Python. It occurs when Python can’t find a file you’re trying to open or interact with. This usually happens because the file path is incorrect, the file doesn’t exist in the specified location, or there’s a typo in the file name.

Common Causes of FileNotFoundError

  • Incorrect file path: The file you’re trying to open doesn’t exist at the specified location.
  • Typos in the file name: Misspelled file names or extensions can lead to this error.
  • Missing files: Sometimes, files are moved or deleted, causing the error when your code tries to access them.

Example

open("data.txt", "r")  # File does not exist

If data.txt doesn’t exist in the current directory, Python will raise a FileNotFoundError.

How to Handle It?

  • Check the file path: Ensure the file exists in the directory you’re trying to access. Use relative or absolute paths carefully.
  • Use os.path.exists() to check if the file exists before opening it:
import os

if os.path.exists("data.txt"):
    with open("data.txt", "r") as file:
        content = file.read()
else:
    print("File not found.")

Use exception handling: To prevent program crashes, handle errors gracefully with a try-except block:

try:
    with open("data.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("Oops! The file is missing.")
📝
Learn how to avoid the Clever Hans Fallacy in SRE tooling by reading our blog on SRE Tooling and the Clever Hans Fallacy.

2. ImportError: The Module Mystery

An ImportError occurs when Python is unable to import a module you’ve specified. This can happen for several reasons, such as a typo in the module name, the module not being installed, or issues with the Python environment.

Common Causes of ImportError

  • Module not installed: If the module isn’t installed in the current environment, Python won’t be able to import it.
  • Typo in the module name: A misspelled module name will lead to an ImportError.
  • Incorrect import statement: Using incorrect syntax or wrong import paths.

Example 1: Module Not Installed

import numpy  # If numpy is not installed

If the numpy module isn’t installed in your environment, Python will raise an ImportError.

How to Handle It?

  • Check if the module is installed: Use pip list to check the installed modules, or use the import statement inside a try-except block:
try:
    import numpy
except ImportError:
    print("Numpy module is not installed.")
  • Install missing modules: If a module is missing, you can install it using pip:
pip install numpy

Example 2: Typo in the Module Name

import mathh  # Misspelled module name

Here, mathh is not a valid Python module, so Python will raise an ImportError.

How to Handle It?

  • Check module spelling: Always double-check the module name for typos.
  • Consult the documentation: If you’re unsure of the module name or its installation process, refer to the official documentation for clarity.

ModuleNotFoundError: A Specific Type of ImportError

The ModuleNotFoundError is a subclass of ImportError, introduced in Python 3.6. This error is more specific and occurs when Python can’t find a module, usually because it’s not installed or available in the current environment.

Common Causes of ModuleNotFoundError

  • Module not installed: The most common cause is the module simply not being installed.
  • Python environment issues: If you’re working with virtual environments, the module might be missing in that specific environment.

Example

import some_nonexistent_module  # Module doesn’t exist

This will raise a ModuleNotFoundError since some_nonexistent_module is not installed or found.

How to Handle It?

  • Check environment configuration: Make sure the module is installed in the correct environment (e.g., virtualenv).
  • Install missing modules: Use pip or conda to install the missing module:
pip install some_nonexistent_module
📝
Check out our blog on Winston Logging in Node.js to enhance your logging practices!

Handling File and Module Errors Gracefully

To ensure your Python programs handle file and module errors gracefully, follow these best practices:

  • Use try-except blocks: Always wrap file and module imports in try-except blocks to catch errors and prevent program crashes.
try:
    import some_module
except ModuleNotFoundError:
    print("Oops! Module not found.")
  • Verify paths and module installations: Before accessing a file or importing a module, ensure that the file exists in the specified path or the module is installed in the environment.
  • Cross-check paths: When working with files, it’s easy to get confused with relative vs. absolute paths. Make sure you're using the correct type of path based on your working directory.
  • Ensure proper environment management: If you’re working with multiple Python environments (like virtualenv), ensure that the required packages are installed in each environment.

IndentationError: The Silent Code Killers

An IndentationError occurs when Python encounters an unexpected indentation in the code. Unlike many other programming languages that rely on braces {} or semicolons to define blocks of code, Python uses indentation (whitespace) to indicate which statements are inside a block. This makes indentation crucial for Python's syntax.

Indentation errors often happen because of inconsistent use of spaces or tabs, or because you’ve left out the necessary indentation altogether.

Common Causes of IndentationError

  • Mixing spaces and tabs: Python does not allow mixing tabs and spaces for indentation in the same block of code. Doing so can cause indentation errors that are tricky to debug.
  • Incorrect indentation level: Forgetting to indent or indenting incorrectly inside a code block (such as a loop, if statement, or function).
  • Accidental misalignment: Sometimes, when you copy and paste code, the indentation can become inconsistent, leading to errors.

Example 1: Mixing Tabs and Spaces

def greet(): 
    print("Hello, world!")
    print("This line uses tabs.")  # This line uses a tab instead of spaces

Here, the second print() statement uses a tab for indentation, while the first uses spaces. This inconsistency raises an IndentationError because Python expects a consistent style of indentation throughout a block.

How to Handle It?

  • Always use spaces or always use tabs: The Python community recommends using spaces (4 spaces per indentation level).
  • Check your IDE settings: Ensure your text editor or IDE is configured to either use spaces or tabs consistently for indentation.
  • Use an IDE with auto-indentation: IDEs like Visual Studio Code or PyCharm automatically format the indentation for you, helping avoid these errors.
📖
You can explore more about effective error logging with Go in our blog on Logging Errors in Go with Zerolog.

Example 2: Incorrect Indentation Level

def greet(): 
    print("Hello, world!")
  print("This line is incorrectly indented.")  # IndentationError

In this example, the second print() statement has an indentation that’s not aligned with the first one. Python expects all code within the same block to have the same level of indentation.

How to Handle It?

  • Maintain consistent indentation: Ensure all statements in the same block are indented at the same level.

Example 3: Forgetting to Indent Inside a Block

if True: 
    print("This will cause an indentation error.")  # IndentationError

In this case, the print() statement should be indented to indicate that it belongs inside the if block. Forgetting to indent it properly results in an IndentationError.

How to Handle It?

  • Indent properly: Python expects all statements following a colon (e.g., after if, for, while, def, etc.) to be indented.
if True:
print("This is correctly indented.")

Tips to Avoid IndentationErrors

  • Stick to 4 spaces: It’s the convention in the Python community to use 4 spaces for each indentation level.
  • Don’t mix spaces and tabs: Ensure you’re using either spaces or tabs throughout your entire codebase. Mixing both creates invisible errors that are tough to troubleshoot.
  • Use linters and formatters: Tools like pylint and black help detect and fix indentation errors automatically.
  • Enable visible whitespace in your editor: Some editors allow you to see spaces and tabs as visible characters, which can be incredibly helpful for spotting inconsistent indentation.
  • Double-check indentation after copy-pasting: When copying and pasting code, double-check the indentation since copying from websites or different editors can mess up the formatting.
📝
For more on managing cron job logs, check out our blog on Crontab Logs.

NameError: The Ghosts of Undefined Variables

A NameError occurs when Python encounters a variable or function name that hasn’t been defined yet or is out of scope. In simple terms, it’s like trying to use something that doesn’t exist in the current context. Whether you misspell a variable or forget to define it entirely, Python will raise a NameError and let you know that it doesn’t know what you're talking about.

Common Causes of NameError

  • Using an undefined variable: Trying to access a variable that hasn’t been defined yet will result in a NameError.
  • Misspelling a variable or function name: Typos in variable or function names are a common cause of NameErrors.
  • Scope issues: If a variable is defined inside a function but is accessed outside of it, you might encounter a NameError due to scope restrictions.
  • Improperly imported functions: If you try to use a function from an imported module without importing it properly, Python won’t recognize it and will throw a NameError.

Example 1: Using an Undefined Variable

print(my_variable)  # NameError: name 'my_variable' is not defined

In this case, my_variable is used before it’s defined. Since Python doesn’t know about this variable, it raises a NameError.

How to Handle It?

  • Define the variable before using it: Always make sure the variable or function is defined before usage.
my_variable = 10
print(my_variable)  # This will work
  • Check the order of your code: Ensure that variables are declared before they’re used.

Example 2: Misspelling a Variable Name

my_variable = 10
print(my_varible)  # NameError: name 'my_varible' is not defined

Here, my_varible is a misspelling of my_variable. Python doesn’t recognize the misspelled version, so it throws a NameError.

How to Handle It?

  • Check your spelling: Double-check variable names for typos, especially when dealing with longer names or complex functions. IDEs with syntax highlighting can help spot these errors.
my_variable = 10
print(my_variable)  # This will work

Example 3: Scope Issues

def my_function():
    x = 5
    print(x)
    
print(x)  # NameError: name 'x' is not defined

In this case, x is defined inside the function my_function(), so it’s only accessible within that function. Trying to access x outside of the function raises a NameError.

How to Handle It?

  • Check variable scope: If you need to use a variable outside of a function, consider returning it or defining it in a broader scope.
def my_function():
    x = 5
    return x

x = my_function()  # Now x is defined
print(x)  # This will work

Example 4: Import Issues

# Assuming math library is not imported
print(math.sqrt(9))  # NameError: name 'math' is not defined

Here, Python doesn’t recognize the math module because it hasn't been imported, raising a NameError.

How to Handle It?

  • Properly import modules: Ensure any external modules or functions are properly imported before use.
import math
print(math.sqrt(9))  # This will work
📝
To dive deeper into structured logging in Go, check out our blog on Understanding Logrus.

Tips for Preventing NameErrors

  • Be mindful of scope: Always ensure that variables are defined before use. Pay attention to variable scope—local vs. global.
  • Check for typos: Misspelling variable or function names is a common cause of NameErrors. Using an IDE with autocomplete and syntax highlighting can help reduce these errors.
  • Use descriptive variable names: Meaningful variable names can make your code easier to read and minimize the chance of typos.
  • Use a linter: Tools like pylint or flake8 can identify undefined variables and other potential issues before running the code.
  • Import modules correctly: Make sure all required modules are imported before using their functions.

Conclusion


Grasping the different types of errors in Python is crucial for every programmer. While syntax and runtime errors are usually easier to spot with the right tools, logical errors can be trickier and often require a more in-depth look at your code.

🤝
If you'd like to dive deeper or discuss anything further, feel free to join our community on Discord. We have a dedicated channel where you can chat with other developers and get help with your specific use case.

Contents


Newsletter

Stay updated on the latest from Last9.

Authors

Preeti Dewani

Technical Product Manager at Last9

Topics

Handcrafted Related Posts