Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Python errors fall into two broad groups: syntax errors, which Python finds while parsing your code, and exceptions, which occur when syntactically valid code runs. As the Python 3.11 tutorial puts it, “There are (at least) two distinguishable kinds of errors: syntax errors and exceptions.”

This guide explains ten errors beginners regularly meet, what each message means, the first check to make, and a small correction pattern. “Common” here is a practical teaching selection, not a measured frequency ranking; the Python documentation does not publish a top-ten frequency table.

A repeatable way to read any Python traceback

Do not start by guessing. Use the traceback as a sequence of clues.

  1. Read the final line first. It names the exception, such as TypeError or FileNotFoundError, followed by a detail message.
  2. Find the relevant source frame. Move upward until you reach your own file and the line number where the failure surfaced. A traceback can include several calls; the bottom frame is usually the immediate failing operation.
  3. Inspect the values and objects on that line. Add temporary checks such as print(type(value), repr(value)), or use a debugger.
  4. Trace the value backward. The line that raises an exception is not always where the bad value was created.
  5. Make the smallest targeted change, then run the same case again. Avoid catching every exception just to hide the traceback.

The tutorial’s explanation of errors, exceptions and tracebacks and the built-in exception reference are the authoritative definitions used below.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

1. SyntaxError

SyntaxError means Python could not parse the program’s form. The code never reaches execution, so changing a variable value or adding a runtime try block cannot fix it.

Typical example

if total > 10
    print(total)

Python points at the line where it detected the problem, but the actual mistake can be immediately before the marker. Here the missing colon ends the if header.

Fix checklist

  • Check the indicated line and the preceding token.
  • Look for missing colons after if, for, while, def, class and try statements.
  • Match parentheses, brackets and braces.
  • Close every quoted string and use consistent quote characters.
  • Check commas, operators and accidental characters copied into the file.
if total > 10:
    print(total)

2. IndentationError and TabError

IndentationError is a SyntaxError subtype involving indentation. TabError is raised when tabs and spaces are used inconsistently. Python uses indentation to define blocks, so alignment is part of the language syntax.

Typical examples

def greet(name):
print("Hello", name)

The function body must be indented:

def greet(name):
    print("Hello", name)

A mixed-indent file may produce TabError: inconsistent use of tabs and spaces in indentation. Configure your editor to insert spaces (four spaces per level is the usual convention), display whitespace, and convert existing tabs consistently. Do not “fix” one line by adding arbitrary spaces; align the entire block with its parent statement.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

3. NameError

NameError means an unqualified local or global name cannot be found when Python evaluates it.

print(usernmae)

In this example the assigned name might be username, but the use contains a spelling error. Python names are case-sensitive.

What to check

  • Compare spelling and capitalization at the assignment and use sites.
  • Confirm the assignment executes before the reference.
  • Check scope: a name created inside a function is not automatically global.
  • Verify that a conditional branch or early return did not skip the assignment.
  • For imports, confirm you used the name actually bound by the import statement.
username = "Ada"
print(username)

4. TypeError

TypeError indicates that an operation or function received an inappropriate type. The type itself is the problem, not merely one particular value.

age = 42
message = "Age: " + age

String concatenation expects strings, but age is an integer. Convert deliberately when that represents the intended meaning:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
message = "Age: " + str(age)
# or
message = f"Age: {age}"

Debugging method

Inspect both operands and the callable’s expected signature:

print(type(left), repr(left))
print(type(right), repr(right))

Do not convert blindly. Turning a malformed object into text may silence the exception while producing incorrect output. If a function expects a list but receives a dictionary, correct the data flow or call the function designed for that structure.

5. ValueError

ValueError means the operation received the right general type but an unacceptable value. The built-in exception reference describes it as an inappropriate argument where no more precise exception applies.

month = int("September")

The argument is a string, which int() accepts in principle, but this particular string is not a valid integer representation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Fix by validating at the boundary

raw = input("Month number (1-12): ").strip()
try:
    month = int(raw)
except ValueError:
    print("Enter a whole number.")
else:
    if not 1 <= month <= 12:
        print("Month must be between 1 and 12.")

Normalize input before conversion, and validate ranges after conversion. Keep the original value available for a useful error message.

6. IndexError

IndexError occurs when a sequence subscript is outside its valid range.

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

Valid indexes are 0 and 1; index 2 is out of range.

Boundary checks

  • Use len(sequence) to inspect the available size.
  • Remember that the last valid zero-based index is len(sequence) - 1.
  • Prefer iteration when you do not need an index: for color in colors:.
  • For paired positions, use enumerate() rather than manually incrementing a counter.
  • Test empty and one-item inputs; off-by-one errors often appear only there.
for index, color in enumerate(colors):
    print(index, color)

7. KeyError

KeyError is raised when a mapping lookup requests a key that is not present.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
settings = {"theme": "dark"}
print(settings["timezone"])

Choose the behavior you actually want

# Required key: fail clearly if it is absent
zone = settings["timezone"]

# Optional key: supply a documented default
zone = settings.get("timezone", "UTC")

# Branch explicitly
if "timezone" in settings:
    zone = settings["timezone"]

Inspect the real keys with print(settings.keys()), including their exact case and whitespace. Do not replace a missing value with a default merely to suppress the exception if the setting is required for correctness.

8. AttributeError

AttributeError means an attribute reference or assignment failed. The object may have a different type than expected, may be None, or may simply not expose the requested attribute.

name = None
print(name.upper())

Here None has no upper method. Find out where the unexpected value entered the program:

print(type(name), repr(name))

Common causes

  • A function returned None because it has no value on one branch.
  • A variable was overwritten with a different object.
  • A method was misspelled, such as uppper().
  • You expected a dictionary, list or library object but received text or a response wrapper.

Fix the producer or the contract between functions rather than adding a conditional that silently skips required work.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

9. ModuleNotFoundError

ModuleNotFoundError is an ImportError subtype raised when Python cannot locate the requested module.

import requests

Environment checklist

  1. Check the spelling and capitalization of the import.
  2. Identify the interpreter running the script: python -c "import sys; print(sys.executable)" (use python3 where that is your command).
  3. Install the package into that same environment, preferably inside an activated virtual environment.
  4. Make sure a local file is not shadowing the intended package name.
  5. Run the program from the expected project directory and verify the environment is active.

A package installed for one Python interpreter is not automatically available to another. The exception reference documents the relationship between ModuleNotFoundError and ImportError.

10. FileNotFoundError

FileNotFoundError means the path supplied to an operation does not resolve to an existing file accessible from the process’s current location.

with open("data/input.csv", encoding="utf-8") as file:
    rows = file.read()

Diagnose the path, not just the filename

  • Print the process working directory with from pathlib import Path; print(Path.cwd()).
  • Check the exact spelling, case and extension.
  • Confirm the file exists where the program expects it.
  • Prefer an explicit pathlib.Path construction for multi-directory projects.
  • Do not assume the working directory is the directory containing the script; IDEs, shells and task runners can choose different directories.
from pathlib import Path

path = Path("data") / "input.csv"
if not path.is_file():
    raise FileNotFoundError(f"Expected input file at {path.resolve()}")
rows = path.read_text(encoding="utf-8")

Exception handling that fixes problems instead of hiding them

Catch the expected exception as specifically as possible. The Python tutorial recommends being specific and allowing unexpected exceptions to propagate. Keep the try block focused so that the handler does not accidentally catch an error from unrelated work.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
try:
    number = int(raw)
except ValueError:
    print("Please enter a whole number.")
else:
    save_number(number)

Use else for success-only work when it makes the boundary clearer. Use finally for cleanup that must happen regardless of success. Avoid except Exception: unless you are at a deliberate application boundary that logs the failure and handles it responsibly. If a lower-level function cannot recover, log useful context and re-raise so its caller can decide what to do.

A practical troubleshooting sequence

  1. Reproduce the error with the smallest input that still fails.
  2. Copy the complete traceback, not only its last line.
  3. Classify it as a parse-time syntax problem or a runtime exception.
  4. Inspect the named line, then print the relevant values, types, path and scope.
  5. Check boundary cases: empty collections, missing keys, invalid text, alternate environments and different working directories.
  6. Apply one change and rerun the reproducer.
  7. Add a regression test for the case once it works.

Or skip the browser setup

If your debugging workflow involves capturing a web page that demonstrates a failing request or UI state, ScreenshotNeo provides a website screenshot API and MCP server. A single request returns a PNG, JPEG, WebP or PDF. Before capture it accepts the cookie or consent banner like a visitor and removes more than 60 known consent platforms, newsletter popups and chat widgets; each cleanup step can be disabled. Bot checks, blank pages, timeouts, failed loads and cache hits are not billed, and the response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers.

For a direct capture, see the ScreenshotNeo API documentation:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Its MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients. The Free plan includes 1,000 shots each month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Short FAQ

Why does Python show an arrow on a line that looks correct?

The parser marks where it realized the syntax could not continue. The missing colon, delimiter or quote is often on that line or immediately before it.

Should I catch every exception at the top level?

Only at a deliberate application boundary where you can report or recover meaningfully. During development, letting unexpected exceptions propagate preserves the traceback needed to fix the cause.

How can I tell whether an import problem is installation or code?

Compare the interpreter path used to run the script with the environment where the package was installed, then verify the import name. Different interpreters commonly have different installed packages.

What is the fastest way to expose a hidden type mismatch?

Print both type(value) and repr(value) immediately before the failing expression. This shows both the runtime type and its exact contents, including surrounding whitespace and None.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Why does Python show an arrow on a line that looks correct?

The parser marks where it realized the syntax could not continue. The missing colon, delimiter or quote is often on that line or immediately before it.

Should I catch every exception at the top level?

Only at a deliberate application boundary where you can report or recover meaningfully. During development, letting unexpected exceptions propagate preserves the traceback needed to fix the cause.

How can I tell whether an import problem is installation or code?

Compare the interpreter path used to run the script with the environment where the package was installed, then verify the import name. Different interpreters commonly have different installed packages.

What is the fastest way to expose a hidden type mismatch?

Print both type(value) and repr(value) immediately before the failing expression. This shows the runtime type and its exact contents, including whitespace and None.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.