7 Common Python Errors and How to Fix Them

Published on: July 10, 2026
Reading time: 5 minutes
Janela de erro com a logo do Python

Python is beginner-friendly, but every programmer still makes mistakes. Errors are not proof that you are bad at coding. They are information that helps you understand what the interpreter expected and what your program actually did.

This guide explains seven common Python errors and habits that frequently slow beginners down. You will see broken examples, corrected versions, and practical strategies for diagnosing problems instead of changing code randomly.

First, Learn to Read a Traceback

When Python stops with an exception, it prints a traceback. Read it from the bottom upward. The last line contains the exception type and message. The lines above show the chain of function calls and the file and line where the failure occurred.

Traceback (most recent call last):
  File "app.py", line 4, in <module>
    result = 10 / value
ZeroDivisionError: division by zero

This message identifies the exception, the file, the line number, and the expression. Reproduce the problem with the smallest possible input, inspect the values involved, and fix the cause rather than hiding the message. The official Python errors and exceptions tutorial is an excellent reference.

1. Incorrect Indentation

Indentation defines blocks in Python. Code inside an if, loop, function, class, or exception handler must be consistently indented.

age = 20

if age >= 18:
print("Adult")

This produces an IndentationError. The statement belongs inside the conditional block:

age = 20

if age >= 18:
    print("Adult")

Use four spaces per level and configure your editor to insert spaces rather than mixing tabs and spaces. Automatic formatting tools can catch inconsistent style. The PEP 8 guide explains common layout conventions.

2. Forgetting That input() Returns Text

The input() function always returns a string. Adding that text directly to an integer causes a TypeError.

age = input("Age: ")
next_year = age + 1

Convert the value before arithmetic and handle invalid input:

try:
    age = int(input("Age: "))
    print(f"Next year you will be {age + 1}.")
except ValueError:
    print("Enter a whole number.")

Use float() for decimal input and int() for whole numbers. The dedicated Python input() guide covers validation patterns in more depth.

3. Choosing the Wrong Data Structure

Lists, tuples, sets, and dictionaries have different purposes. A list preserves order and can contain duplicates. A tuple is immutable. A set stores unique hashable values. A dictionary maps keys to values.

# A list is awkward for repeated membership checks
blocked_users = ["ana", "leo", "mia"]

if "leo" in blocked_users:
    print("Blocked")

The code works, but a set better expresses uniqueness and normally provides faster membership checks:

blocked_users = {"ana", "leo", "mia"}

if "leo" in blocked_users:
    print("Blocked")

Use a dictionary when records need labels:

product = {
    "name": "Keyboard",
    "price": 89.90,
    "stock": 12,
}

print(product["name"])

Read the Python sets guide and the broader Python data types guide before forcing every problem into a list.

4. Catching Every Exception Without Understanding It

Exception handling keeps a program from failing unexpectedly, but a broad empty handler can hide real bugs.

try:
    value = int(user_text)
except:
    pass

This discards useful information. Catch the expected exception and provide an appropriate response:

try:
    value = int(user_text)
except ValueError as exc:
    print(f"Invalid integer: {exc}")

Different failures need different actions. A missing file may require a new path; invalid input should be requested again; a database outage may need a retry or alert. The complete try and except guide explains else, finally, custom exceptions, and exception chaining.

5. Writing Everything in One Long Script

A program may begin with ten lines and grow to hundreds. When all logic stays at the top level, repeated code appears, variables become difficult to track, and testing individual behavior becomes painful.

name = input("Name: ")
age = int(input("Age: "))
print(f"Hello {name}, you are {age} years old.")

Move clear responsibilities into functions:

def read_age() -> int:
    while True:
        try:
            return int(input("Age: "))
        except ValueError:
            print("Enter a whole number.")


def greet(name: str, age: int) -> str:
    return f"Hello {name}, you are {age} years old."


name = input("Name: ").strip()
age = read_age()
print(greet(name, age))

Each function now has one job and can be tested separately. Continue with the Python functions guide.

6. Installing Every Package Globally

Different projects may require different versions of the same library. Global installation makes dependencies collide and creates the familiar problem of code working on one computer but not another.

python -m venv .venv

Activate the environment, install only the project’s dependencies, and record them:

# Windows
.venv\Scripts\activate

# macOS or Linux
source .venv/bin/activate

python -m pip install requests
python -m pip freeze > requirements.txt

Use python -m pip to make it clearer which interpreter owns the installed package. The venv guide includes activation commands and editor configuration. For missing packages, see how to fix ModuleNotFoundError.

7. Ignoring Naming, Formatting, and Documentation

Code that runs is not automatically easy to maintain. Unclear names, giant functions, unexplained constants, and outdated comments create bugs later.

# Hard to understand
def c(a, b):
    return a * b * 0.15

A clearer version communicates intent:

TAX_RATE = 0.15


def calculate_tax(price: float, quantity: int) -> float:
    """Return the tax for a product order."""
    subtotal = price * quantity
    return subtotal * TAX_RATE

Use descriptive snake_case names for functions and variables, constants in uppercase, useful docstrings, and comments that explain why rather than restating what the code says. The guides to Python comments and Python docstrings provide practical examples.

Other Frequent Exceptions

NameError

A variable or function name does not exist in the current scope. Check spelling and whether the assignment ran before use.

total = 25
print(totla)  # NameError: typo

IndexError

A sequence index is outside its valid range.

colors = ["blue", "green"]
print(colors[2])

Inspect len(colors), use loops rather than manual indexes when possible, or validate the index first.

KeyError

A dictionary does not contain the requested key.

user = {"name": "Sam"}
print(user["email"])

Use get() when absence is expected:

email = user.get("email")
if email is None:
    print("No email registered")

AttributeError

An object does not have the requested attribute or method. Check its type and the method name.

number = 10
number.append(5)  # integers have no append method

A Reliable Debugging Process

  1. Read the complete traceback, especially the final line.
  2. Open the exact file and line mentioned.
  3. Inspect the value and type of every variable in that expression.
  4. Reduce the problem to a small reproducible example.
  5. Check the official documentation for the function or exception.
  6. Change one thing at a time.
  7. Add a test that prevents the bug from returning.

The official built-in exceptions reference lists the meaning and inheritance of standard exception classes. For automated regression tests, use the Pytest beginner guide.

Use print() Carefully for Debugging

Temporary output can reveal values and execution flow:

def calculate_average(values):
    print(f"DEBUG values={values!r}")
    total = sum(values)
    print(f"DEBUG total={total}")
    return total / len(values)

Remove noisy prints or replace them with logging before production. The f-string debugging guide shows the useful debug specifier.

Frequently Asked Questions

What is the most common beginner error?

Indentation and type conversion are among the first recurring problems because Python uses indentation for blocks and input() returns text.

Should I catch Exception everywhere?

No. Catch specific, expected exceptions near the operation that can fail. Let unexpected programming errors remain visible during development.

Why does code work in one terminal but not another?

The terminals may use different Python interpreters or virtual environments. Check the active interpreter and install dependencies inside the project environment.

Is PEP 8 mandatory?

Python does not require it to execute code, but consistent style improves readability, reviews, teamwork, and maintenance.

How do I become better at debugging?

Practice reading tracebacks, isolate small examples, verify types and assumptions, and write tests for every corrected bug.

Conclusion

The fastest way to improve is not to avoid every error but to understand each one. Use consistent indentation, convert external input, choose appropriate data structures, handle expected exceptions, organize logic into functions, isolate dependencies, and follow clear style conventions. These habits turn confusing failures into precise, manageable problems.

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    logotipo do Python em azul e amarelo ao lado das palavras 'try except' em fonte amarela sobre um fundo azul-texturizado
    Error Resolution
    Foto de perfil de Leandro Hirt da Academify

    Python try and except: Complete Beginner Guide

    Learn Python try and except with specific exceptions, else, finally, raise, chaining, custom errors, input validation, files, requests, logging, and

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    Uso de f-strings para debug e formatação em Python
    Error Resolution
    Foto de perfil de Leandro Hirt da Academify

    Debug Python with f-Strings: Practical Guide

    Learn to debug Python with f-strings using the debug specifier, repr, type checks, number formatting, loops, functions, exceptions, logging, and

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    Como resolver UnicodeDecodeError em arquivos Python
    Error Resolution
    Foto de perfil de Leandro Hirt da Academify

    Fix Python UnicodeDecodeError Simply

    Fix Python UnicodeDecodeError: always specify encoding, use chardet to auto-detect, handle CSV files with Pandas, and apply try/except fallback.

    Ler mais

    Tempo de leitura: 3 minutos
    03/06/2026
    Como resolver problemas de caminhos de arquivos em scripts Python
    Error Resolution
    Foto de perfil de Leandro Hirt da Academify

    Fix Python FileNotFoundError: Path Guide

    Fix Python FileNotFoundError: understand absolute vs relative paths, use pathlib and os.getcwd(), handle errors with try/except, and build a reliable

    Ler mais

    Tempo de leitura: 3 minutos
    03/06/2026
    Como resolver erros de codificação UTF-8 em Python
    Error Resolution
    Foto de perfil de Leandro Hirt da Academify

    Fix Python UTF-8 Encoding Errors

    Fix Python UTF-8 encoding errors: always specify encoding when opening files, handle UnicodeDecodeError, auto-detect with chardet, and write a safe

    Ler mais

    Tempo de leitura: 4 minutos
    03/06/2026
    Como corrigir erro ModuleNotFoundError em Python rapidamente
    Error Resolution
    Foto de perfil de Leandro Hirt da Academify

    Fix Python ModuleNotFoundError Fast

    Fix Python ModuleNotFoundError: check missing packages, typos, virtual environments, sys.path issues, and file name conflicts with practical examples.

    Ler mais

    Tempo de leitura: 8 minutos
    03/06/2026