Python from zeroBeginnerLesson 1057 min read

Reading errors without fear

Error messages are clues, not punishments. Learn the four errors you will meet most often, and how to read a traceback from the bottom up.

Lesson in motion

In 60 seconds

Reading errors without fear

Error messages are clues, not punishments. Learn the four errors you will meet most often, and how to read a traceback from the bottom up.

1/5
In simple words
When a car's warning light comes on, a good mechanic does not panic. They read which light it is and look in the right place. Python's error messages are warning lights. They tell you what kind of problem it is and which line to look at.
Do this
Every programmer, beginner or expert, gets errors every day. Fixing them is a normal part of coding, and each one you fix makes you better. You are doing it right.

What an error looks like

When Python cannot continue, it stops and prints a traceback. Here is one (the file name may look a little different in your browser):
What Python printstext
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    print(report("Asha", 85))
  File "main.py", line 2, in report
    return "Marks for " + name + ": " + marks
TypeError: can only concatenate str (not "int") to str

Read it from the bottom up

  1. 1

    Last line: the kind of error and a message

    TypeError: can only join text (str) to text, not a number (int).
  2. 2

    Just above: the line where it broke

    Line 2, inside the function report.
  3. 3

    Further up: how Python got there

    Line 5 called report(), which ran line 2.
  4. 4

    Now fix the line

    Turn the number into text: str(marks), or use an f-string.
The bottom line tells you what went wrong. The lines just above tell you where. The top part tells you the path Python took to get there, which helps when the error is inside a function.

The four errors you will meet most

ErrorWhat it meansCommon causeHow to fix
SyntaxErrorPython cannot understand the code at all, so nothing runsMissing :, bracket or quote markLook at the line shown and the line just before it
NameErrorYou used a name Python does not knowA typo, wrong capital letter, or using a variable before creating itCheck the spelling and that it was created first
TypeErrorYou used a value of the wrong type for this jobAdding text to a number; calling a function with the wrong number of argumentsConvert with int() or str(), or fix the call
IndexErrorYou asked for a list position that does not existCounting to len(list) instead of stopping before itRemember the last index is len(list) - 1

SyntaxError: the grammar check

Python checks the grammar of the whole program before running any of it. So with a SyntaxError, nothing is printed at all, not even the lines above the mistake. Two common ones:
Examples of SyntaxError messagestext
if marks > 35              <- missing colon
SyntaxError: expected ':'

print("Hello"              <- missing closing bracket
SyntaxError: '(' was never closed
Sometimes Python points to the line after the real mistake, because that is where it got confused. If the line shown looks fine, check the one above it.

NameError and TypeError in action

Python: catching errors to look at thempython
# try/except lets the program carry on after an error, so we can see each one.
try:
    total = 10
    print(totl)                 # typo
except NameError as e:
    print("NameError:", e)

try:
    print("Age: " + 13)         # text + number
except TypeError as e:
    print("TypeError:", e)

try:
    runs = [4, 6, 1]
    print(runs[3])              # only positions 0, 1, 2 exist
except IndexError as e:
    print("IndexError:", e)
You do not need try and except yet. They are used here only so one example can show three errors. Normally you just let the error appear, read it, and fix the code.

A calm fixing routine

  1. Read the last line. Which kind of error is it?
  2. Find the line number. Look at that line, and the one above it.
  3. Say out loud what that line is trying to do, and what each value is.
  4. Change one thing. Press Run again.
  5. New error? Good: that means the first one is fixed and Python got further.
Note
Adding print() lines to see what a variable holds is a real debugging method that professionals use too. For example print("marks is", marks, type(marks)) shows both the value and its type.
Try this. In the error examples above, fix each mistake so no error happens: spell total correctly, use str(13), and ask for runs[2]. Press Run after each fix.

Watch and read more

Lab

A buggy marks report, fixed one error at a time by reading each traceback.

~15 min

The problem

This program has three bugs. It is meant to print a student's average, their top mark and how many subjects they passed.

  1. Press Run. Read the traceback from the bottom up. Which error is it, and which line?
  2. Fix just that one thing and press Run again. A new error means progress!
  3. Keep going until all three lines print correctly: the average of [78, 92, 65, 88] is 80.75, the top mark is 92, and 4 subjects are passed (pass mark 35).

Do not delete the functions or change what they are for: fix the bugs inside them. Then press Check. 🎉

Practice lab

Edit the code and run it. Python runs in your browser — nothing is sent to our server.

Output

No output. Add print(...) to see values.

You are done when

Hard questions

Try to answer before you reveal. If you can answer these, you understood the lesson.

Q1The TypeError appeared on the first print line, but the real mistake was inside report. How does the traceback show you both places?Reveal

The traceback lists each step. Near the bottom it shows the line inside report where the text and number were joined; above that it shows the print(report(...)) line that called it. Reading bottom-up takes you straight to the line to fix, and the lines above explain how Python got there.

Q2Why did you only see one error at a time, when there were three bugs?Reveal

Python stops at the first error it meets while running. The IndexError and NameError are in lines that had not run yet. Only after the first fix could Python get far enough to reach the next bug. (A SyntaxError is different: Python finds it before running anything.)

Please sign in to continue.

Questions people ask

Why does Python say 'most recent call last'?

It lists the steps in the order they happened, so the newest one, where the error actually occurred, is at the bottom. That is why reading from the bottom up is the quickest way in.

The error points to a line that looks correct. What now?

Check the line above it, especially for a missing bracket or quote mark. Also check that the values used on that line are what you think they are, by printing them just before it.

Should I copy error messages into a search engine or a chatbot?

It can help, especially the last line. But first try to read it yourself; you will learn much faster. If you ask a chatbot, share the error and the few lines around it, and make sure you understand the fix before using it.

What does 'Did you mean' in an error mean?

Newer versions of Python often suggest a similar name when you make a typo, for example a NameError may end with a hint like Did you mean: 'total'?. It is usually right, so it is worth reading.

Lesson test

5 questions. Get 3 right (60%) to pass and complete this lesson.

Sign in to take the test and save your progress