Common Python Errors and How to Fix Them by Reading the Traceback

Traceback (most recent call last):

  File "ticket_report.py", line 18, in <module>
    owner = ticket["assigned_to"]
KeyError: 'assigned_to'

You are looking at a Python script that reads support tickets. The file came from a class project, a small portfolio exercise, or a real work queue. The question is not “How do I make Python stop complaining?” It is: does the data lack an owner, or did the program make an unsafe assumption?

Python

A traceback is a trail of evidence. If you learn to read it from the bottom up, reproduce the failure, and test one explanation at a time, you can debug more clearly whether you are studying in a community-college lab, working through a library course, or preparing a small project to discuss in an interview.

Start at the last line, then climb upward

Python’s official Errors and Exceptions tutorial distinguishes syntax errors from exceptions. A traceback is Python’s record of the call path that led to an exception. The final line usually tells you the exception type and its message; the lines above it help you locate the code path.

In the example, the final line is KeyError: 'assigned_to'. Python was asked for a dictionary key that was not present. The highlighted line is where the exception became visible:

owner = ticket["assigned_to"]

That line does not prove that Python is broken. It gives you a fact: this particular ticket did not contain the requested key at that moment.

Is the input wrong, or is the assumption wrong?

Make the data visible before changing the code:

ticket = {"id": 1042, "subject": "Cannot reset password"}

print(ticket)
owner = ticket["assigned_to"]

The dictionary contains an ID and a subject, but no assigned_to. You have at least two plausible explanations:

  • The upstream data contract says every ticket must contain an owner, so the input is incomplete.
  • Unassigned tickets are valid, so the program should represent that state instead of indexing the key directly.

Do not catch the exception blindly. The official Python built-in exceptions reference tells you what KeyError means, but it cannot tell you whether an unassigned ticket is valid for your product or class project. That is a requirement decision, not a syntax decision.

For a safe display-only report, this may be appropriate:

owner = ticket.get("assigned_to", "Unassigned")
print(owner)

For a system where every ticket must have an owner before it is exported, silently using “Unassigned” could hide bad data. In that case, a validation error with a useful message may be safer. The same traceback can lead to different corrections because the intended behavior is different.

Case file: a CSV that works in class but fails on another computer

Imagine a beginner in an evening Python course in Austin opening a file created during a campus lab session:

with open("tickets.csv", "r", encoding="utf-8") as file:
    rows = file.readlines()

On the classroom computer, the script works. At home, it produces:

Traceback (most recent call last):
  File "ticket_report.py", line 1, in <module>
    with open("tickets.csv", "r", encoding="utf-8") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'tickets.csv'

The last line says that Python could not find the requested path from the program’s current working directory. It does not necessarily mean the file was deleted. The file might be in Downloads, the project folder might be different, or the filename might differ in capitalization.

Ask Python where it is looking:

from pathlib import Path

print(Path.cwd())
print(Path("tickets.csv").exists())

Now you have an observable check. If the path is wrong, fix the project layout or pass the correct path. Avoid “fixing” the error by hard-coding a private path such as /Users/your-name/Downloads/tickets.csv; that may work on your Mac and fail on a Windows teammate’s computer.

A small project can use a predictable layout:

ticket-project/
├── data/
│   └── tickets.csv
└── ticket_report.py
from pathlib import Path

DATA_FILE = Path(__file__).parent / "data" / "tickets.csv"

with DATA_FILE.open("r", encoding="utf-8") as file:
    rows = file.readlines()

This is not a universal path solution for every application. It is a useful way to make the example independent of the folder from which the command was launched. When the code moves to a hosted service, a container, or a company system, configuration and deployment rules matter too.

That distinction is part of the work. The Bureau of Labor Statistics describes computer support specialists as people who diagnose user problems, explain solutions, and install or repair hardware and software. A support-minded response to this traceback records the operating system, working directory, project structure, and exact command instead of sending back “try reinstalling Python.”

Case file: the list index that does not exist

Now consider a script that prints the first result from a search:

results = []
first_result = results[0]
print(first_result)

The traceback ends with:

IndexError: list index out of range

The name is precise: the requested position is outside the list. The problem is not fixed by changing 0 to 1; that would ask for a different position that also does not exist.

Ask what an empty search should display:

if results:
    print(results[0])
else:
    print("No matching tickets found.")

This small branch connects a Python error to an interface decision. A QA tester might record “empty search result crashes the report.” A support specialist might need to reproduce the exact search terms. A developer might add a regression test so the empty case stays visible.

def first_result_message(results):
    if results:
        return results[0]
    return "No matching tickets found."

assert first_result_message(["Ticket 1042"]) == "Ticket 1042"
assert first_result_message([]) == "No matching tickets found."

The O*NET profile for Software Quality Assurance Analysts and Testers includes identifying, analyzing, and documenting problems, writing test cases, retesting fixes, and maintaining defect records. You are not becoming a QA professional by writing two assertions, but you are practicing the same evidence pattern: input, expected result, observed result, and a repeatable check.

The value is the right type—but not the right value

A different script reads a number from a form or CSV file:

quantity = input("How many tickets? ")
total = quantity * 2
print(total)

The code may produce repeated text such as "55" when you expected 10. Or a conversion might fail:

quantity = int("five")
ValueError: invalid literal for int() with base 10: 'five'

Python received a string, and the requested integer conversion could not interpret that value. The value has the wrong content for the operation, even though the expression is syntactically valid.

raw_quantity = input("How many tickets? ").strip()

try:
    quantity = int(raw_quantity)
except ValueError:
    print("Enter a whole number, such as 5.")
else:
    print(quantity * 2)

Do not use except Exception: just to make the traceback disappear. Catch the narrow exception you understand, give the user a useful next action, and decide whether invalid input should be rejected, corrected, or recorded. A data-entry script for a class project and a production payroll process do not have the same tolerance for silent recovery.

If you study Python through NYPL TechConnect’s Python-related classes, a public course may give you a place to practice this distinction with other beginners. If you use a self-directed path, the official Python tutorial and a small local test file can provide the same basic experiment. Check the current class schedule and access requirements; a library listing is not a guarantee that a class is currently open.

A traceback is not the same as a bug report

A traceback tells you what happened in one execution. A useful report tells someone else how to see it and what should happen instead.

Expected: An unassigned ticket appears with the label “Unassigned.”

Actual: The report stops with KeyError: 'assigned_to'.

Steps: Load ticket-1042.json; run python ticket_report.py; select the password-reset ticket.

Environment: Windows 11, Python version, project commit, input-file version.

Scope: Do not change the input schema or add a dependency.

That vocabulary—expected, actual, steps to reproduce, environment, scope—is useful when you are explaining a problem to an instructor, a teammate, a support colleague, or an interviewer. It also prevents an AI assistant from guessing what “fix” means.

If you use AI to discuss the traceback, remove API keys, passwords, customer records, private URLs, and proprietary logs first. Send the smallest example that still shows the behavior. Ask for two possible causes and one test for each. Then verify the answer against Python’s documentation and your own run.

What changes when the code moves from your laptop to a team?

A beginner’s project can often be repaired with a print statement, a small branch, and an assertion. A shared project needs more communication. A production system may need review, logging, monitoring, rollback, privacy controls, and a test that protects the fix.

The Google Engineering Practices guide to small changes explains why focused changes are easier to review, test, merge, and revert. The pytest documentation shows how Python projects can express expected behavior with tests and assert that exceptions are raised. These practices do not turn every beginner script into a production system; they give you a sensible direction when the consequences grow.

For a first portfolio artifact, keep the scope honest. Save the original failing example, the corrected code, one regression test, the command you ran, and a short explanation of what remains untested. Do not describe a classroom script as production experience. Describe the evidence accurately: “I reproduced an empty-input failure, changed the behavior, and added a test for the empty case.”

A small market note for beginners

Recent U.S. labor-market reports deserve careful reading. The BLS outlook for software developers, quality assurance analysts, and testers covers broad occupations and experienced workers; its projections and median wages are not entry-level guarantees. The Indeed Hiring Lab’s 2026 analysis reported a market tilted toward seniority in its own job-posting data, while the NACE survey on entry-level AI skills reported growing employer interest in AI-related abilities.

The practical reading is not “Python guarantees work” or “beginners have no chance.” It is that a learner should practice more than syntax: reproduce a problem, read documentation, test an edge case, communicate clearly, and explain the limits of a fix. Those are useful habits across development, QA, support, and data work, even though each occupation has different requirements.

Make the next traceback useful

Choose one small script and create three failures on purpose:

  1. Remove a dictionary key and observe the KeyError.
  2. Pass an empty list and observe the IndexError.
  3. Pass text that cannot become an integer and observe the ValueError.

For each one, write the same five lines:

Expected:
Actual:
Likely cause:
Smallest test:
Next safe change:

That page of notes is more useful than a list of exception names. A traceback gives you a location. Your job is to turn that location into a question, a test, and an explanation another person can use.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top