Error Messages

debugging
beginner
Read tracebacks and recognize common beginner error patterns.
  • Level: Beginner
  • Estimated time: 35–50 minutes
  • You will learn: Read tracebacks and recognize common beginner error patterns.
  • Practice in: Colab, VS Code, and the terminal

Questions

  • What problem does Error Messages help us solve in a small Python program?
  • What should we predict before running the example?
  • What value, output, or error should we inspect after changing one line?

Objectives

  • Run a complete example for Python error messages in Colab.
  • Explain the example line by line using plain language.
  • Change one part of the code and predict the result before running it.
  • Recognize one common mistake and use the error message as evidence.

Hands-on episode: Error Messages

A traceback is a stack of clues. Start near the bottom for the error type and message, then look upward for the file name, line number, and expression Python was running.

We will learn this by running code, not by memorizing a definition first. Open the Colab notebook from the button above, find this section, and run each cell in order. Keep a small note beside the notebook with three columns: prediction, actual result, and what changed.

Example 1.1

Predict the error type before running, then read the traceback from bottom to top.

scores = [10, 8, 9]
print(scores[3])

Run the cell once without editing it. If the result is different from your prediction, leave the prediction visible and write one sentence about the difference. That sentence is more useful than a perfect first guess.

Explain Example 1.1

  • The list has three items, so its valid positive indexes are 0, 1, and 2.
  • scores[3] asks for a fourth item that does not exist.
  • Python raises IndexError, and the message tells you the index is outside the list’s range.

Now explain the example out loud or in a Markdown cell. Use short sentences: “this line creates…”, “this name stores…”, “this output appears because…”. If you cannot explain a line yet, run only the lines above it and inspect the values that exist at that moment.

Challenge 1.1

NoteChallenge

Change the index to 2 and run again. The program now succeeds, which confirms that the bug was the position, not the list itself.

Show a safe way to approach the challenge
  1. Copy Example 1.1 into a new Colab cell.
  2. Change exactly one value, name, condition, or line.
  3. Write the expected output before running the cell.
  4. Run the cell and compare the actual result with your prediction.
  5. If the result surprises you, undo the change and try a smaller one.

Suggested first move: Change the index to 2 and run again.

Debugging checkpoint 1.1

WarningDebugging checkpoint

Do not rewrite the whole program after seeing a traceback. First underline four clues: error type, error message, line number, and the smallest expression on that line. Then make one change and rerun.

Do not debug by rewriting the whole example. Read the error type or surprising output, inspect the closest value with print(...) or type(...), then change one thing. This is the same routine you will use in larger projects.

Apply it

Create one NameError, one TypeError, one IndexError, and one KeyError in Colab. For each, write a one-sentence diagnosis before fixing it.

Finish by adding a Markdown cell that answers: What did this example teach me that I can reuse in a project?

Key points

  • Learn the concept by running a complete, small example first.
  • Predict before execution so your thinking becomes visible.
  • Change one thing at a time so cause and effect stay clear.
  • Treat errors as clues about the exact line or value Python could not handle.

The problem this lesson solves

Every programmer sees error messages. Beginners often read a traceback as a wall of red text, but it is actually a structured report. Python is telling you where it stopped, what kind of problem it found, and which clue to inspect first.

An error message is not a judgment about you. It is feedback from the Python interpreter: “I followed your instructions until this point, and here is why I could not continue.”

Tiny vocabulary

Word Beginner-friendly meaning
Program The instructions you wrote.
Interpreter The tool that reads and runs Python code.
Exception Python’s formal word for many runtime errors.
Traceback The multi-line report Python prints after many errors.
Frame One step in the traceback, often with file, line, function, and code.
Error type The label at the end, such as TypeError or NameError.

How to read a traceback

A traceback is easier to read when you use the same order every time: bottom clue, location, suspicious expression, small experiment.

flowchart TD
  red["Python prints red traceback"] --> bottom["Read the bottom line<br/>error type + message"]
  bottom --> location["Find file and line number"]
  location --> code["Inspect the expression on that line"]
  code --> values["Check names, values, and types"]
  values --> experiment["Change one thing and run again"]

Do not start by rewriting the whole program. Start by extracting one clue.

1. Reading a traceback slowly

Consider this program:

# average.py

def average(values):
    total = sum(values)
    return total / len(values)

scores = [10, 8, "9", 7]
print(average(scores))

The list contains one string, "9", mixed with integers. When Python tries to sum the list, it cannot add an integer and a string.

A traceback may look like this:

Traceback (most recent call last):
  File "average.py", line 7, in <module>
    print(average(scores))
  File "average.py", line 4, in average
    total = sum(values)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

The two most useful places to look

  1. Look at the last line first.
    • TypeError is the error type.
    • The message says Python tried to use + with an int and a str.
  2. Look for a file and line number you recognize.
    • File "average.py", line 4, in average points to the line where Python discovered the problem.
    • The line is total = sum(values).

The line number is not always the original cause. Here, the cause is earlier: "9" was put into the list as text. But the traceback still gives an excellent place to start investigating.

What to inspect next

Ask small questions:

  • What is the error type?
  • Which line was Python running?
  • Which values were involved?
  • Are the types what I expected?

A helpful temporary print would be:

print(scores)
print([type(score) for score in scores])

This reveals that one item is a string.

Check your understanding

2. Common beginner errors

Different error types point to different first checks.

Error type Beginner meaning First thing to check
SyntaxError Python could not understand the code structure. Missing colon, quote, parenthesis, or invalid = use.
IndentationError A block is not indented the way Python expects. Lines after if, for, while, def, or class.
NameError Python does not know this name. Spelling, assignment order, and scope.
TypeError A value is the wrong kind for this operation. Use type(...) and check conversions.
ValueError The type is acceptable, but this specific value is not. Bad conversion such as int("twelve").
IndexError A list/string index is outside the valid range. len(...) and the index being used.
KeyError A dictionary key is missing. dict.keys(), spelling, and .get(...).
AttributeError This value does not have the method/attribute used. Type of the value and method spelling.

Examples and fixes

NameError

Broken code:

print(total)
total = 10

Python reads top to bottom. At the first line, total does not exist yet. Fix:

total = 10
print(total)

TypeError

Broken code:

total = "2" + 3

"2" is text and 3 is an integer. Decide what you mean:

print(int("2") + 3)   # arithmetic: 5
print("2" + "3")      # text joining: 23

IndexError

Broken code:

numbers = [1, 2, 3]
print(numbers[5])

The list has length 3, so valid indexes are 0, 1, and 2. Fix by using a valid index or by checking the length first.

KeyError

Broken code:

person = {"name": "Ada"}
print(person["email"])

The key "email" is missing. Fix with a check or .get():

print(person.get("email", "No email saved"))

Check your understanding

3. A calm debugging routine

When you see an error, use the same routine every time.

The five-step routine

  1. Read the last line. What is the error type and message?
  2. Find your file and line. Which line was Python running?
  3. Inspect values and types. What are the names on that line? What do they contain?
  4. Make one small change. Do not rewrite the whole program.
  5. Run again and compare. Did the error move, disappear, or change type?

Example 1

Broken code:

price = input("Price: ")
quantity = input("Quantity: ")
total = price * quantity
print(total)

Likely error:

TypeError: can't multiply sequence by non-int of type 'str'

Apply the routine:

  1. Last line says TypeError: wrong kind of value for multiplication.
  2. The suspicious line is total = price * quantity.
  3. input() returns strings, so both names hold text.
  4. Convert to numbers:
price = float(input("Price: "))
quantity = int(input("Quantity: "))
total = price * quantity
print(total)

A good debugging sentence

After fixing an error, write one sentence:

The error happened because input() returned text; converting price and quantity before multiplication made the operation numeric.

If you can explain the fix, you are learning—not just guessing.

Check your understanding

Key points

TipKey points
  • A traceback is a structured clue report, not a personal failure.
  • Start with the last line: it names the error type and message.
  • Then find a file and line number you recognize.
  • The reported line is where Python noticed the problem; the cause may be earlier.
  • Check values and types before making large changes.
  • Change one thing at a time and run again.

References

  • Python Tutorial: errors and exceptions: https://docs.python.org/3/tutorial/errors.html
  • Python built-in exceptions: https://docs.python.org/3/library/exceptions.html
Back to top