…
…
Python Programming Fundamentals · Lesson 5 / 40 · Error messages and getting help
PreviewIn this lesson you will
help() outputYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
A new intern has joined Corner Café and tried to "fix" a few lines of the receipt program. Now the program does not run, there are strange red lines on the screen, and the intern suggests rewriting everything from scratch. In this lesson we will learn to read those lines and repair the program in a few minutes.
At the end of the lesson, the program the intern broke will print this receipt again:
OutputMost expensive: 4.25
Cash difference: 0.75
Total: $5.25In this lesson you will learn three things: the order in which to read an error message, the four error types you will meet most often, and how to ask about a function you do not know. None of it asks you to memorize anything; it is all a reading habit.
Everyone who writes programs gets errors. Someone who has coded for years and someone who started today both see dozens of error messages in a day. The difference is that the experienced person reads the message, while the beginner sees it, panics, and deletes the code. Yet the moment Python finds the error, it gives you three pieces of information: what happened, where it happened, and on which line. Rewriting the code without reading it is like someone who has a map in their hands searching for the route again without looking at the map.
An error message usually starts with Traceback (most recent call last):. Roughly, that means "a trace going backwards: the most recent call is at the bottom". This sentence says "read downward". The most important line of the message is always the bottom line. There you first find the error type (such as NameError), and after the colon a short explanation. One line above it is a line number such as line 3, and below that the code of that line, with ^ marks underlining the problem spot.
Example 1 (case): The intern's total line. The intern wrote the price and the quantity correctly, but misspelled a name on the third line:
price = 4.25 qty = 2 print("Total:", pirce * qty)
The message Python gives:
OutputTraceback (most recent call last):
File "<kod>", line 3, in <module>
print("Total:", pirce * qty)
^^^^^
NameError: name 'pirce' is not defined. Did you mean: 'price'?Start from the bottom. Last line: NameError, meaning Python does not recognize a name; the name it does not recognize is pirce. One line up: the problem is on line 3. Below that: the code of line 3, with pirce marked by ^^^^^. Since Python 3.10, a suggestion is added to the end of the message: Did you mean: 'price'?. You read three lines and found the problem: write price instead of pirce.
When you run your code on this site, the error box shows the two most important parts of the report: the last line (NameError: name 'pirce' is not defined) and the line number (line 3). Below them a short plain-language explanation appears under the heading "What does this mean?". The Did you mean suggestion does not appear in the box on the site; you see it when you run Python on your own computer. Whatever environment you are in, the reading order is the same: type, explanation, line.
Now try to work out what you can from a message alone, without seeing the code.
You cannot see the code, only this message. What can you say for certain from the message?
Traceback (most recent call last): File "<kod>", line 4, in <module> TypeError: can only concatenate str (not "int") to str
This error has one more feature: the program ran up to this line. Python runs the lines one by one from top to bottom; when a line has a problem it stops there and writes the report. The work done by earlier lines stays on the screen, and later lines never run. Change the value of price below and see this for yourself.
Change the value of price: which lines run, and what stays on the screen?
Pick a value; predict the output first, then look.
1price = 4.252qty = 23print("Calculation started")4total = price * qty + 105print("Total:", total)
Calculation started Total: 18.5
Faded lines didn't run with this value. With price = "4.25", price * qty puts the string side by side twice ("4.254.25"), and then + 10 tries to add a number to a string, so a TypeError occurs on line 4. The output Calculation started stays on the screen because line 3 ran before the error; line 5 never runs.
Let's leave one misconception here: the thought "if I got an error, I failed" is wrong. An error message is a note the program writes to you. The faster you read it, the faster you move forward.
In the first lessons of the unit you already met four error types. Putting them side by side makes the differences clearer:
| Type | What it means | Typical cause | Where to look first |
|---|---|---|---|
SyntaxError | A syntax rule is broken; Python cannot read the code | An unclosed quote or parenthesis, a missing comma | The marked line and the line just above it |
NameError | Python does not recognize this name | Misspelling a name or using different letter case, using it before defining it | Compare the line where the name is defined with the line where it is used |
TypeError | The type of the value does not fit this operation | Joining a string and a number with +, len(85) | The types of the values on the line (str or int?) |
ValueError | The type is right, but the value is not suitable | int("three"), |
SyntaxError is very different from the other three. Python reads a program from start to finish before running it. If this reading finds a place that breaks a syntax rule, it does not run the program at all; not even the first line runs. There is also no Traceback line at the top of the message, because there was no run to trace backwards. NameError, TypeError and ValueError occur while running, when Python reaches that line; the lines before it have run.
Example 2 (case): Four small broken lines. Four lines from the intern's experiments, each with its real message:
print("Corner Café"
Message:
Output File "<kod>", line 1
print("Corner Café"
^
SyntaxError: '(' was never closedprint(totl)Message:
OutputNameError: name 'totl' is not definedprint("Table " + 7)
Message:
OutputTypeError: can only concatenate str (not "int") to strprint(int("three"))
Message:
OutputValueError: invalid literal for int() with base 10: 'three'In the first, Python says the opened parenthesis was never closed (was never closed). In the second, there is nothing called totl; most likely total was meant. In the third, a number was being added to a string. The fourth is the most interesting: int() accepts a string, so the type is right; but "three" is not written with digits, so it cannot be converted to an integer. The pattern invalid literal for int() with base 10 means "this string is not an integer in base ten". Calling a function with an unsuitable type also gives a TypeError: if you write len(85) you get TypeError: object of type 'int' has no len(), because a number has no length.
Now match each line with the result it gives. One of them gives no error, so be careful.
What happens when each line runs?
For each row, pick its match from the list, then check.
print(Latte)"4" + 5int("ten")print("Tea:, 1.25)len(85)print("3" * 2)Now test the "no line runs" rule of SyntaxError.
What appears on the screen when this three-line program is run?
print("Opening") print("Latte:", 4.25 print("Closing")
The lines in Example 2 contained print, int and len. These are all functions: ready-made code that has a name and does a specific job. Using a function is called calling it. To call it, you write its name, open a parenthesis right after it, and put inside the values the function will work on. These values are called arguments; if there are several, they are separated by commas: max(4.25, 2.00, 1.25).
Most functions produce a result. When max(4.25, 2.00, 1.25) runs, 4.25 takes its place. You can print this result with print, put it in a variable, or use it in another calculation. You can also nest functions; Python runs the innermost call first and passes its result to the outer one. In the line print(max(85, 40)), max runs first and produces 85, then print prints that value.
Let's add three new ones to the functions you already know, such as print, round, len, type and int:
| Function | What it does | Example | Result |
|---|---|---|---|
max | Produces the largest of the given values | max(4.25, 2.00, 1.25) | 4.25 |
min | Produces the smallest of the given values | min(4.25, 2.00, 1.25) | 1.25 |
abs | Drops the sign of a number (absolute value) | abs(-15) | 15 |
Example 3 (case): The most expensive item and the cash difference. At the end of the day, Ada wants to know the most expensive and the cheapest item, and also the difference in the register. The register should have had $60, but when counted it came to $59.25. She wants to know how much the difference is, not whether it is short or over; abs drops the sign:
print("Most expensive:", max(4.25, 2.00, 1.75)) print("Cheapest:", min(4.25, 2.00, 1.75)) expected = 60 counted = 59.25 print("Cash difference:", abs(counted - expected))
OutputMost expensive: 4.25
Cheapest: 1.75
Cash difference: 0.75On the last line, counted - expected is calculated first and gives -0.75, then abs(-0.75) makes it 0.75, and finally print prints it. Reading from the inside out is the easiest way to understand long lines.
Match each call with the result it produces.
For each row, pick its match from the list, then check.
max(4.25, 2.00, 1.25)min(4.25, 2.00, 1.25)abs(-15)round(2.7)len("Corner Café")max(3, abs(-7))Watch out for one misconception: a function does not change the variable you give it. Writing abs(result) does not change the value inside the result variable; it only produces a new value. If you do not give this value to anything, it is lost. You will see the sneakiest example of this in the "Common mistake" section at the end of the lesson.
helpPython has hundreds of ready-made functions; nobody memorizes all of them. What matters is knowing how to find out what to give a function and what you get from it when you see it for the first time. Your first source of help is Python itself: if you write help(name), Python prints the description of that function on the screen. You give the function's name without parentheses: help(abs); if you write help(abs()), abs first tries to run and you get an error.
Example 4 (case): `abs` describes itself.
help(abs)OutputHelp on built-in function abs in module builtins:
abs(x, /)
Return the absolute value of the argument.For long functions the output can fill the screen, but the two lines after the heading are often enough. The first is the signature: abs(x, /) says the function takes one value (x). You can ignore the / at the end for now. The second is a one-sentence description: "Return the absolute value of the argument." In plain words: it takes a value and produces its unsigned form. A few words that often appear in descriptions: *return* (produce, give back), *argument*, *optional*, *default* (the value used when none is given).
Try this yourself in the cell below. First run it and read the first lines. Then write max instead of abs and run it again: how many values can max take? The arg1, arg2, *args part of the signature means "two or more values".
Try it now· not graded; doesn't affect progress
Let's turn what you have learned so far into a routine you will apply to every error. First, read the last line of the message: what is the type, and what does the explanation say? Second, go to the line number shown and read the code on that line together with the message. Third, change only one thing on that line and run again. If you change three things at once, you cannot tell which one worked; and if a new error appears, you lose track of where it came from. If a program has more than one error, Python shows only the first each time. When you fix one and run again, the next one appears; this shows you are moving forward, not backward.
The fastest way to get to know errors is to produce them on purpose. If you break working code yourself, you see which change gives which message; later, when you meet that message, you recognize the cause immediately.
Example 5 (outside the case): The day's temperature difference. Morning -3 degrees, noon 12 degrees. How many degrees is the difference between them, and what is the highest temperature of the day?
morning = -3 noon = 12 print("Difference:", abs(morning - noon)) print("Highest:", max(morning, noon))
OutputDifference: 15
Highest: 12The calculation morning - noon gives -15; a difference cannot be negative, so abs drops the sign. In the cell below, the same code is ready to run. Do three things in order, read the last line of the message after each, and undo the change: (1) Change the name abs to Abs. (2) Delete the closing quote in the "Difference:" string. (3) Write "-3" instead of -3. You will see three different error types: which are they?
Try it now· not graded; doesn't affect progress
(1) gives a NameError: Python is case-sensitive, so Abs and abs are different names. (2) gives a SyntaxError and no line runs. (3) gives TypeError: unsupported operand type(s) for -: 'str' and 'int': you cannot subtract a number from a string.
Now put the routine in the right order.
You have run into an error message. Put the steps in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
One last warning: not getting an error message does not mean the program is correct. Python only catches lines that break the rules; it does not notice a wrong calculation. That is why you should compare the output of every program with the result you expect.
The program the intern left behind is below. We fix the errors one by one, applying the reading routine.
# 1. Highest-priced item print("Most expensive:", max(4.25, 2.00, 1.75) # 2. Cash difference expected = 60 counted = 59.25 print("Cash difference:", Abs(counted - expected)) # 3. Total of the basket qty = 3 price = 1.75 total = qty * price print(f"Total: ${total:.2f}")
On the first run, nothing is written to the screen, only this message appears:
Output File "<kod>", line 2
print("Most expensive:", max(4.25, 2.00, 1.75)
^
SyntaxError: '(' was never closedThere is no Traceback line and the type is SyntaxError: the program did not run at all. Two parentheses were opened on line 2 (print( and max(), but only one was closed. We add a ) to the end of the line and run again:
OutputMost expensive: 4.25
Traceback (most recent call last):
File "<kod>", line 6, in <module>
print("Cash difference:", Abs(counted - expected))
^^^
NameError: name 'Abs' is not defined. Did you mean: 'abs'?There is progress: the first line was printed, because this error occurred while running, on line 6. Python does not recognize the name
Not giving the result of a function to anything. This mistake gives no message, which is why it is the hardest to notice. Someone who wants to round the price to two decimal places writes this:
price = 4.256 round(price, 2) print(price)
4.256 appears on the screen. There is no error message, but the result is wrong. Why? round(price, 2) produces a new value (4.26), but since we gave this value to nobody, it is lost; the value in the price box never changes. The correct way is to put the produced value back into the box: price = round(price, 2). Or to write print(round(price, 2)) directly.
What does this program print?
price = 4.256 round(price, 2) print(price)
line N shows the line where it was noticed, and the code below shows the problem spot; then change one thing on that line and run again.SyntaxError is a syntax error and stops the program from running at all; NameError (unrecognized name), TypeError (unsuitable type) and ValueError (unsuitable value) occur while running, when Python reaches that line.help(name) and read the signature and the first sentence.Next lesson: In the unit task you will rewrite Corner Café's receipt from scratch using all five lessons.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
int("3.75")| The value shown in quotes |
Absabs# 1. Highest-priced item print("Most expensive:", max(4.25, 2.00, 1.75)) # 2. Cash difference expected = 60 counted = 59.25 print("Cash difference:", abs(counted - expected)) # 3. Total of the basket qty = 3 price = 1.75 total = qty * price print(f"Total: ${total:.2f}")
OutputMost expensive: 4.25
Cash difference: 0.75
Total: $5.25Two errors, two single changes, and the rest of the code untouched. If we had rewritten it from scratch as the intern suggested, it would have taken longer and we might have added new errors.