Python

How to understand and handling errors in Python

Learn how to understand Python errors, read tracebacks, handle exceptions, and debug programs using practical examples and techniques.

joao • 30 Oct 2026 • 14 min read • 500 • 0
How to understand and handling errors in Python | Usando Python
Publicidade

Errors are an unavoidable part of programming. Whether you are writing your first Python script or working on a complex application, you will eventually encounter situations where your code does not behave as expected.

For beginners, error messages can initially seem confusing or even intimidating. However, learning to understand these messages is an essential part of becoming a better programmer.

Python provides detailed information whenever something goes wrong. By learning how to interpret tracebacks, recognize common error types, and apply systematic debugging techniques, you can solve problems more efficiently and write more reliable code.

In this guide, we will explore the most common Python errors, understand why they occur, and learn practical techniques for identifying and fixing them.

1. Understanding Python Tracebacks

When Python encounters an error that prevents a program from continuing, it usually displays a traceback.

A traceback is a report that shows where the error occurred and the sequence of function calls that led to it. It contains useful information, including the file name, line number, function involved, and the type of error.

Let's look at a simple example:

def favorite_icecream():
    icecream = [
        'chocolate',
        'vanilla',
        'strawberry'
    ]

    print(icecream[3])

favorite_icecream()

If you execute this code, Python will display an error similar to this:

Traceback (most recent call last):
  File "main.py", line 11, in <module>
    favorite_icecream()
  File "main.py", line 8, in favorite_icecream
    print(icecream[3])
IndexError: list index out of range

The problem occurs because the list contains only three elements. Python uses zero-based indexing, meaning the valid positions are 0, 1, and 2. Attempting to access position 3 raises an IndexError.

How to Read a Traceback

A traceback may contain several lines, especially when multiple functions are involved. Understanding its structure makes debugging much easier.

Pay attention to the following elements:

  • File name: Identifies the file where the execution took place.
  • Line number: Shows the location associated with each function call.
  • Function name: Indicates which function was executing.
  • Error type: Identifies the category of the problem.
  • Error message: Provides additional information about what went wrong.

A useful habit is to start reading the traceback from the bottom. The final line normally contains the exception type and its message, while the preceding lines help you trace the execution path.

Long tracebacks do not necessarily indicate serious problems. They often mean that several functions were called before the error occurred.

2. Common Types of Python Errors

Python has several built-in exceptions, each representing a particular type of problem. Understanding their differences helps you identify the cause of an error and choose an appropriate solution.

2.1. SyntaxError

A SyntaxError occurs when Python cannot understand the structure of your code.

This usually happens when a programming statement does not follow Python's syntax rules.

For example:

def sum_function()
    message = 'Hello World'
    print(message)

The function definition is missing a colon (:).

Python will report:

SyntaxError: expected ':'

To fix the problem, add the missing colon:

def sum_function():
    message = 'Hello World'
    print(message)

Other common causes of syntax errors include:

  • Missing colons after if, for, while, def, and class statements.
  • Unclosed parentheses, brackets, or braces.
  • Missing quotation marks in strings.
  • Incorrectly structured expressions.
  • Misplaced operators.

2.2. IndentationError

Indentation is particularly important in Python because it defines code blocks.

Unlike languages that use curly braces to organize blocks of code, Python relies on indentation to determine which statements belong together.

Consider this example:

def sum_function():
    message = 'Hello World'
    print(message)
        return message

The return statement has unnecessary indentation, causing Python to raise an error.

IndentationError: unexpected indent

The corrected version is:

def sum_function():
    message = 'Hello World'
    print(message)
    return message

To avoid indentation problems:

  • Use four spaces for each indentation level.
  • Be consistent throughout your project.
  • Avoid mixing spaces and tabs.
  • Configure your code editor to use spaces instead of tabs.

2.3. Mixing Spaces and Tabs

Another indentation-related problem occurs when spaces and tabs are mixed within the same code block.

For example:

def calculate():
    message = 'Hello World'
    print(message)
	return message

In this example, the final line may contain a tab character while the previous lines use spaces.

Depending on the surrounding code, this can result in a TabError or another indentation-related error.

Python provides a useful module for detecting inconsistent indentation:

python -m tabnanny your_file.py

In Visual Studio Code, you can also use the Command Palette and select Convert Indentation to Spaces.

2.4. Runtime Errors

Runtime errors occur while a program is executing.

Unlike syntax errors, these problems are not necessarily detected before execution. The code may be syntactically correct but still fail when Python encounters an invalid operation or unexpected value.

Let's examine some common runtime exceptions.

IndexError

An IndexError occurs when you try to access an index that does not exist in a sequence, such as a list or tuple.

numbers = [10, 20, 30]

print(numbers[5])

The list contains only three elements, so index 5 is invalid.

Output:

IndexError: list index out of range

One way to prevent this problem is to check the length of the list before accessing an element.

TypeError

A TypeError occurs when an operation or function is used with an inappropriate data type.

number = 10
text = "20"

result = number + text

Python cannot directly add an integer and a string.

Output:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

If the intention is to perform a numerical calculation, convert the string to an integer:

number = 10
text = "20"

result = number + int(text)

print(result)

Output:

30

ValueError

A ValueError occurs when a function receives an argument of the correct type but with an inappropriate value.

For example:

number = int("hello")

The int() function accepts a string, but the string must represent a valid integer.

Output:

ValueError: invalid literal for int() with base 10: 'hello'

You can prevent this problem by validating the input or handling the exception appropriately.

KeyError

A KeyError occurs when you try to access a dictionary key that does not exist.

person = {
    'name': 'Alice',
    'age': 25
}

print(person['email'])

Since the dictionary does not contain an email key, Python raises an exception.

One alternative is to use the get() method:

print(person.get('email', 'Not available'))

Output:

Not available

AttributeError

An AttributeError occurs when you attempt to access an attribute or method that an object does not have.

For example:

numbers = [1, 2, 3]

numbers.push(4)

Python lists do not have a push() method. To add an element to a list, use append():

numbers.append(4)

print(numbers)

Output:

[1, 2, 3, 4]

3. Reference Table of Common Python Errors

The following table summarizes some frequently encountered Python exceptions and their typical causes.

Error TypeWhen It OccursTypical Solution
SyntaxErrorInvalid Python syntaxCheck punctuation and statement structure
IndentationErrorIncorrect indentationUse consistent indentation
TabErrorInconsistent use of tabs and spacesConvert indentation to spaces
TypeErrorInvalid operation between data typesCheck or convert data types
ValueErrorValid type but inappropriate valueValidate the supplied value
IndexErrorAccessing an invalid sequence indexCheck the sequence length
KeyErrorAccessing a missing dictionary keyCheck the key or use get()
AttributeErrorAccessing a non-existent attributeVerify the object's methods and attributes
NameErrorReferencing an undefined variableDefine the variable before using it
ZeroDivisionErrorDividing a number by zeroCheck the denominator
FileNotFoundErrorAttempting to open a non-existent fileVerify the file path
ImportErrorAn import cannot be completedCheck the module and import statement
ModuleNotFoundErrorPython cannot find a moduleCheck the installation and import path

4. Strategies for Debugging Python Code

Finding an error is only the beginning. The next step is understanding why it happened and determining the correct way to fix it.

Rather than making random changes to your code, follow a systematic debugging process.

Step 1: Read the Complete Traceback

Do not immediately jump to the line where the error appears.

Read the complete traceback and identify the exception type, message, file name, and line number.

These details often provide enough information to understand the problem.

Step 2: Reproduce the Error

Run your program again and observe when the error occurs.

Does it happen every time? Does it only happen with a particular input? Does it appear after a specific operation?

Being able to reproduce an error makes it easier to investigate its cause.

Step 3: Isolate the Problem

If your application contains several functions or large blocks of code, try to identify the smallest section responsible for the problem.

You can temporarily simplify the code or create a small example that reproduces the same error.

This technique is particularly useful when working with larger applications.

Step 4: Make One Change at a Time

Avoid changing several parts of your program simultaneously.

Make one modification, execute the code again, and observe the result.

This helps you understand which change actually solved the problem.

Step 5: Test the Solution

A program that runs without raising an exception is not necessarily correct.

Verify that the output is what you expected and test different inputs, including unexpected or invalid values.

5. Practical Debugging Techniques

Python provides several tools and techniques that can help you investigate problems in your programs.

5.1. Using print() for Debugging

One of the simplest debugging techniques is using print() to display variable values during execution.

For example:

def calculate_average(numbers):
    print(f"Input: {numbers}")

    if not numbers:
        return 0

    total = sum(numbers)

    print(f"Sum: {total}")

    return total / len(numbers)


result = calculate_average([10, 20, 30])

print(f"Average: {result}")

Output:

Input: [10, 20, 30]
Sum: 60
Average: 20.0

By displaying intermediate values, you can understand how data changes throughout your program.

Although simple, this technique is useful for identifying incorrect values, unexpected results, and problems in program logic.

5.2. Using Python's Debugger (pdb)

For more detailed debugging, Python includes a built-in debugger called pdb.

It allows you to pause program execution, inspect variables, and execute code step by step.

Example:

import pdb


def buggy_function(data):
    pdb.set_trace()

    result = data[10]

    return result


buggy_function([1, 2, 3])

When Python reaches pdb.set_trace(), execution pauses and opens an interactive debugging session.

Some useful debugger commands include:

CommandDescription
nExecute the next line
sStep into a function
cContinue execution
p variableDisplay a variable's value
lDisplay the surrounding source code
qQuit the debugger

The pdb module is especially useful when you need to understand how your program behaves internally.

5.3. Handling Exceptions with try and except

Sometimes errors are expected and should be handled without terminating the program unexpectedly.

Python provides the try and except statements for this purpose.

Consider a program that asks the user to enter a number:

user_input = input("Enter a number: ")

try:
    number = int(user_input)
    print(f"You entered: {number}")

except ValueError:
    print("Please enter a valid integer.")

If the user enters text instead of a valid integer, Python raises a ValueError. The except block catches the exception and displays a helpful message.

You can also handle multiple exceptions separately:

try:
    number = int(input("Enter a number: "))
    result = 100 / number

except ValueError:
    print("Please enter a valid number.")

except ZeroDivisionError:
    print("Division by zero is not allowed.")

else:
    print(f"Result: {result}")

finally:
    print("Program execution finished.")

The different blocks have specific purposes:

  • try: Contains the code that might raise an exception.
  • except: Handles an exception when it occurs.
  • else: Executes when no exception occurs in the try block.
  • finally: Executes whether an exception occurs or not.

A good practice is to catch specific exceptions instead of using except Exception indiscriminately. This makes your code easier to understand and prevents unexpected problems from being hidden.

6. Common Programming Mistakes and How to Fix Them

Some errors appear frequently because of small misunderstandings about Python's behavior.

Let's examine three practical examples.

Example 1: Off-by-One Errors

An off-by-one error happens when a loop or index uses an incorrect boundary.

Consider this example:

numbers = [10, 20, 30, 40]

for i in range(len(numbers)):
    print(numbers[i + 1])

The loop eventually attempts to access an index that does not exist.

A simpler solution is to iterate directly over the elements:

for number in numbers:
    print(number)

If you need the index as well, use enumerate():

for index, number in enumerate(numbers):
    print(index, number)

This approach is generally more readable and avoids unnecessary index calculations.

Example 2: Comparing Different Data Types

The input() function always returns a string, even when the user enters a number.

For example:

age = input("Enter your age: ")

if age > 18:
    print("Adult")

This code raises a TypeError because Python cannot directly compare a string with an integer.

Convert the input before performing the comparison:

age = int(input("Enter your age: "))

if age > 18:
    print("Adult")

For applications that accept user input, remember to handle invalid values as well.

Example 3: Missing Imports

Another common mistake is using a function without importing the module or function that provides it.

Incorrect example:

random_number = randint(1, 10)

This raises a NameError if randint has not been defined in the current namespace.

Correct example:

from random import randint

random_number = randint(1, 10)

print(random_number)

Alternatively, import the complete module:

import random

random_number = random.randint(1, 10)

Both approaches are valid. The important point is understanding where the functions you use come from.

7. Developing a Better Approach to Errors

Learning Python is not about writing code without mistakes. It is about developing the ability to recognize problems, understand their causes, and solve them.

When an error appears, avoid immediately copying a solution from the internet or asking an AI tool to rewrite your entire program.

Instead, try to understand what happened first.

A few habits can make a significant difference:

  • Read error messages instead of ignoring them.
  • Understand the purpose of the code that produced the error.
  • Test small sections of your program independently.
  • Use meaningful variable and function names.
  • Validate external input before processing it.
  • Write tests for important functions.
  • Document unusual problems and their solutions.
  • Review your code after fixing an error.

Online resources and AI coding assistants can also help explain unfamiliar errors. However, the most valuable outcome is understanding the underlying problem rather than simply obtaining a working replacement.

8. Creating Custom Exceptions in Python

As you begin developing larger applications, you may encounter situations where Python's built-in exceptions do not adequately describe a particular problem in your application.

In these cases, you can create custom exceptions.

A custom exception is a class that inherits from Python's Exception class.

For example, imagine you are developing a banking application. You might want to raise a specific exception whenever a customer attempts to withdraw more money than their account balance allows.

class InsufficientFundsError(Exception):
    """Raised when an account has insufficient funds."""
    pass


class BankAccount:

    def __init__(self, balance):
        self.balance = balance

    def withdraw(self, amount):
        if amount > self.balance:
            raise InsufficientFundsError(
                f"Cannot withdraw {amount}. "
                f"Available balance: {self.balance}"
            )

        self.balance -= amount

        return self.balance

You can then handle the custom exception:

account = BankAccount(500)

try:
    account.withdraw(1000)

except InsufficientFundsError as error:
    print(f"Transaction failed: {error}")

Output:

Transaction failed: Cannot withdraw 1000. Available balance: 500

Custom exceptions make applications easier to maintain because they allow you to represent application-specific problems with meaningful names.

They are particularly useful in projects involving business rules, APIs, databases, and complex application logic.

9. Quick Reference: Common Python Error Solutions

Error MessagePossible CauseWhat to Check
SyntaxError: invalid syntaxIncorrect syntaxColons, parentheses, quotes, and operators
IndentationError: unexpected indentIncorrect indentationSpaces and indentation levels
TypeErrorIncompatible data typesVariable types and operations
ValueErrorInvalid valueInput and conversion operations
IndexError: list index out of rangeInvalid list indexList length and index boundaries
KeyErrorMissing dictionary keyAvailable dictionary keys
AttributeErrorMissing attribute or methodObject type and available methods
NameErrorUndefined variable or functionVariable names and imports
ZeroDivisionErrorDivision by zeroDenominator value
FileNotFoundErrorFile does not exist at the specified pathFile name and location
ModuleNotFoundErrorModule cannot be foundPackage installation and environment

10. Final Checklist for Debugging Python Programs

Before considering an error resolved, go through this checklist:

  • Read the complete traceback.

  • Identify the exception type.

  • Locate the relevant file and line number.

  • Understand the error message.

  • Reproduce the problem.

  • Isolate the section responsible for the error.

  • Make one change at a time.

  • Test the corrected code.

  • Check how the program behaves with different inputs.

  • Document the solution when necessary.

Conclusion

Errors are a natural part of software development. Even experienced programmers encounter them regularly, whether they are working with simple scripts, web applications, databases, or complex systems.

The ability to understand and resolve errors is one of the most important skills you can develop as a Python programmer.

Start by learning to read tracebacks, become familiar with common exceptions, and practice using debugging tools. Over time, you will begin recognizing familiar patterns and solving problems with greater confidence.

Remember that becoming a better programmer does not mean avoiding every error. It means understanding what went wrong, why it happened, and how to prevent similar problems in the future.

Practice Challenge

The best way to improve your debugging skills is through practice.

Create a Python file and deliberately introduce the following errors:

  1. SyntaxError: Remove the colon from a function definition.
  2. IndentationError: Introduce inconsistent indentation.
  3. IndexError: Try accessing an element outside a list's valid range.
  4. TypeError: Attempt to add a string to an integer.
  5. ValueError: Try converting an invalid string into an integer.
  6. KeyError: Access a dictionary key that does not exist.
  7. ZeroDivisionError: Divide a number by zero.

Run your program after introducing each error. Read the traceback, identify the problem, and correct the code.

Try solving each problem before looking for an answer online.

The more you practice debugging, the more comfortable you will become with Python and the better prepared you will be to build real-world applications.

🎯 Test your knowledge

Take the interactive quiz on this topic and check your score.

Take the Quiz
Publicidade
Você ainda não está logado, por favor faça login ou registre-se para comentar
    0 pessoas participaram | 0 comentários
    Ainda não há comentários, fique à vontade para conversar!