Reading error messages¶
~15 min ยท prerequisite: Arithmetic
What you will be able to do¶
- Find the error type, the message, and the line number in a Python error report.
- Tell apart a syntax error, which stops the program before it runs, from a runtime error, which happens while it runs.
- Fix an error by reading the line it points to and the message that explains it.
The idea¶
When Python cannot continue, it stops and prints an error report. Every report has the same structure, and once you know where to look, it tells you what went wrong and where.
Here is an example from the arithmetic lesson.
Traceback (most recent call last):
File "division.py", line 1, in <module>
print(10 / 0)
~~~^~~
ZeroDivisionError: division by zero
Read it in this order:
- The last line is the most important. It has the form
ErrorType: message. Here the type isZeroDivisionErrorand the message isdivision by zero. The type names the category of the problem, and the message explains it in words. - The
Fileline says where it happened.division.pyis the file, andline 1is the line number. Line numbers start at 1. - The indented line below the
Fileline shows the statement that was running. - The marks under the code (
^and~) point at the part that failed. Their exact shape varies between Python versions, so treat them as a hint. - The whole block is called a traceback. Each
Fileentry above the last line is a step that led to the error, with the most recent step last.
A syntax error is different. Python checks the whole file's grammar before it runs any line, so the program never starts. The report looks like this:
File "greet.py", line 1
print("Hello)
^
SyntaxError: unterminated string literal (detected at line 1)
A runtime error happens while the program runs, so earlier lines may already have run. NameError and ZeroDivisionError are runtime errors.
Two habits help. Fix the first error in the report and run again, because one mistake can cause others below it. Then read the line the report points to, and check what the message says about it.
Python sometimes adds a hint such as Did you mean: 'print'?. Check that the hint matches what you meant.
You will learn try and except properly in Part 4. Here they only check message text.
Python version and error messages
The code and the error messages in this course were tested on Python 3.12 and 3.14. Error wording changes slightly between versions, so the message on your screen may not match the lesson word for word. That is normal. If your message differs, copy the code and the error into an AI assistant and ask it to explain the difference and give you updated code for your version.
Worked example¶
Here is a program with a mistake on the second line.
Line by line, this is what Python does:
total = 4creates a variable namedtotaland stores 4 in it. This line runs without problems.print(totl * 2)tries to read a variable namedtotl. The program has no such name, because the first line createdtotal. Python stops here.
The report is:
Traceback (most recent call last):
File "example.py", line 2, in <module>
print(totl * 2)
^^^^
NameError: name 'totl' is not defined. Did you mean: 'total'?
The type is NameError and the line is 2. The hint suggests total, so fix the spelling on line 2.
Try it¶
Each block causes an error on purpose, catches it with try and except, and checks the message with assert.
Common mistakes¶
-
Reading only the first line of the report. The first line says
Traceback, which tells you nothing about the problem. Scroll to the last line. -
Fixing a different line from the one reported. A
SyntaxErroroften points to the place where Python first noticed a problem, which can be later than the real cause. For example, a missing closing bracket is reported at the open bracket:Look at the bracket that was never closed, then add the
). -
Mixing a number and text. Writing
print(2 + "3")gives:The message says which two types cannot work together. Convert one of them.
-
Using a name before it has a value. Writing
c = b + 1beforeb = 2gives:Move the line that creates
babove the line that uses it.
Practice¶
-
Read this report and write the error type, the message, and the line number in a comment.
-
The following program has one error. Find it, fix it, and run it. The final assert should pass.
-
The following program stops with a
TypeError. Explain in a comment why, and fix it so the assert passes.Hint: this block does not run in the browser because it calls
input. Run it in your terminal with18as the answer. -
Predict the error type for
print(7 / 0). Then run it and compare. - Stretch: write a program that uses
tryandexceptto catch aValueErrorfromint("twelve"), store the message in a variable namedmessage, and assert that the message starts withinvalid literal.
Solution
-
The error type is
NameError, the message isname 'score' is not defined, and the line is 3. -
The name
pricis misspelled. Change line 3 tototal = price * quantity. The assert then passes. -
The value of
inputis a string, soage + 1tries to add a number to text. Convert it withint:
With the answer 18, the assert passes.
-
The error type is
ZeroDivisionError, and the message isdivision by zero. -
python try: number = int("twelve") except ValueError as error: message = str(error) assert message.startswith("invalid literal")
Recap¶
- The last line of an error report gives the error type and a message. The
Fileline gives the file and line number. - A syntax error stops the program before it runs. A runtime error happens while the program runs.
- Fix the first error in the report, read the line it points to, and then run again.