…
…
Python Programming Fundamentals · Lesson 17 / 40 · Errors, debugging, and tests
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Corner Café's intern used what he learned in the last two lessons to split the end-of-day report into two functions: one calculates the average receipt, the other prepares the report line. On Monday everything was fine; on Tuesday the café was closed for renovation, the report ran with a day of 0 sales, and the screen filled with red lines. The intern says "there are three separate errors, let me rewrite everything"; in this lesson we will read that message and repair the report with a single fix.
At the end of the lesson, the repaired report will print the following without crashing, both on a day with sales and on a day without sales:
OutputAverage receipt: $7.75
Average receipt: no salesIn lesson 5 you read the error messages of one-line programs: the last line told you the type and description of the error, and the line N part told you where it was. We thought of those messages as a "crime scene report". Now your programs are made of functions, and one function calls another. When the error happens at the innermost point of this chain, the report gets longer: a message with three, four, sometimes ten levels arrives. In this lesson you will learn three things: in which order to read a multi-level message, which message points to which cause, and why the place where an error is seen is often different from its cause.
Why is this needed? In a one-line program, the place of the error was one place. In a program written with functions, the same line can be called from different places with different values. The average_receipt function ran the same line on Monday and on Tuesday; on Monday there was no problem, on Tuesday there was. The information "there is an error on line 2" is not enough; you also need to know who brought it there, and with which value. The traceback records exactly that.
Example 1 (case): The intern's end-of-day report. The report first writes the line for Monday ($62 revenue, 8 sales), then for Tuesday ($0, 0 sales):
def average_receipt(revenue, sales_count): return revenue / sales_count def day_report(revenue, sales_count): avg = average_receipt(revenue, sales_count) return f"Average receipt: ${avg:.2f}" print(day_report(62, 8)) print(day_report(0, 0))
What appears on the screen (in Python on your own computer):
OutputAverage receipt: $7.75
Traceback (most recent call last):
File "<code>", line 9, in <module>
print(day_report(0, 0))
~~~~~~~~~~^^^^^^
File "<code>", line 5, in day_report
avg = average_receipt(revenue, sales_count)
File "<code>", line 2, in average_receipt
return revenue / sales_count
~~~~~~~~^~~~~~~~~~~~~
ZeroDivisionError: division by zeroThe first thing to notice is at the very top: Average receipt: $7.75. The program raised an error, but it is not true that nothing ran; line 8 ran without a problem and printed its result. The error happened in the call that starts on line 9. The idea that "if a program raised an error, no line has run" is wrong; it is true only for syntax errors (SyntaxError, IndentationError).
Now the message itself. Every File "<code>", line N, in name line is a stop, and the code of that line sits under it. in <module> means "in the main code", that is, in lines that are not inside any function. in day_report means "inside the day_report function", and in average_receipt means "inside average_receipt". The phrase most recent call last in the first line means "the latest call is at the bottom": the stops are listed from top to bottom in the order the program went. The main code called day_report on line 9, day_report called average_receipt on line 5, and average_receipt stopped while doing the division on line 2.
The "crime scene report" from lesson 5 is still valid: the bottom line says what happened. The package analogy adds the route history to it. The reading order has three steps. First, read the bottom line: the type is ZeroDivisionError, the description is division by zero. Second, look at the File block right above it: the error happened on line 2, inside average_receipt. Third, go up one block: it was reached from line 5 of day_report; above that is line 9 of the main code. The ~~~~~^~~~~ marks under the lines also show which part of the line caused the problem: the ^ is under the division operator, and the ~ are under the values on both sides of the division. Some lines have no marks; this means the whole line is the problematic call.
When people see a long message, the idea that "there are multiple errors" comes to mind. In Example 1 there are three File blocks but a single error and a single last line. The blocks are not three separate errors, they are three stops of a single error. Try this by reading only the message, without seeing the code.
You cannot see the code, only this message. In which line of which function did the error happen?
Traceback (most recent call last): File "<code>", line 9, in <module> print(day_report(0, 0)) ~~~~~~~~~~^^^^^^ File "<code>", line 5, in day_report avg = average_receipt(revenue, sales_count) File "<code>", line 2, in average_receipt return revenue / sales_count ~~~~~~~~^~~~~~~~~~~~~ ZeroDivisionError: division by zero
The layers in a traceback are a record of a journey the program would have made even if no error had happened. The main code calls a function, the flow goes down into that function; if that function calls another one, the flow goes down one more level; with return, each level gives its result to the one above and comes back up. Step through the error-free program below and notice how the flow goes down from the main code to receipt_line, and from there to price_with_tax, and comes back. If an error happened in the innermost level, the traceback would write every step of this descent as a File block.
Run the code line by line: see which line runs next, the variable boxes and the output.
def price_with_tax(price, qty): return price * qty * 1.1 def receipt_line(item, price, qty): amount = price_with_tax(price, qty) return f"{item} x{qty}: ${amount:.2f}" line = receipt_line("Latte", 4.25, 2) print(line)
OutputLatte x2: $9.35When you run code on this site, the error box shows the two most important parts of the report: the last line (type and description) and the number of the line where the error happened, that is, the line of the bottom File block. It does not show the stops in between; you see them when you run Python on your own computer. The full messages in this lesson were taken from there. Reading is the same on the site too: the line number in the box is where the error happened, and who brought it there you find by looking at the calls in the code.
Why is this needed? The longest way to find an error is to suspect every line one by one. But every error type points to a first cause to check. Just as a doctor who sees fever and a cough together first thinks of a few specific illnesses, when you see the pattern in the message, you first think of a few specific causes. Let's add the new ones that come with functions next to the four types in lesson 5 (SyntaxError, NameError, TypeError, ValueError):
| Type | Pattern in the message | Likely cause | First place to look |
|---|---|---|---|
ZeroDivisionError | division by zero | The divisor was 0 | Where does the value of the divisor come from? |
TypeError | missing 1 required positional argument: 'qty' | An argument is missing in the call | The line that calls the function |
TypeError | unsupported operand type(s) for -: 'float' and 'NoneType' | A helper function does not return, so None comes back | The end of the function that produces that value |
TypeError | can't multiply sequence by non-int of type 'float' | A string arrived where a number was expected | The type of the argument (are there quotes?) |
TypeError appears three times in the table. This is why the misconception "TypeError is always adding a string and a number" is dangerous: the same type can describe a missing argument, a function that does not return, or a string being multiplied by a number. After reading the type, always read the description after the colon too; the real clue is there.
Example 2 (case): A missing argument. While writing the call inside receipt_line, the intern forgot qty. The rest of the code is the same as the program you stepped through; only line 5 became amount = price_with_tax(price). Python's message:
OutputTraceback (most recent call last):
File "<code>", line 8, in <module>
line = receipt_line("Latte", 4.25, 2)
File "<code>", line 5, in receipt_line
amount = price_with_tax(price)
TypeError: price_with_tax() missing 1 required positional argument: 'qty'In this message the bottom block is line 5 of receipt_line; price_with_tax was never entered, because the call itself was wrong. The description says by name which parameter of which function is missing: qty was not given to the price_with_tax() function. The call error you saw in lesson 15 is now one level longer because it comes from inside a function.
Example 3 (case): `print` instead of `return`. A helper function that gives 10 percent off bills of $10 and above:
def get_discount(amount): if amount >= 10: print(amount * 10 / 100) def total_due(amount): return amount - get_discount(amount) print(total_due(12.5))
What appears on the screen:
Output1.25
Traceback (most recent call last):
File "<code>", line 8, in <module>
print(total_due(12.5))
~~~~~~~~~^^^^^^
File "<code>", line 6, in total_due
return amount - get_discount(amount)
~~~~~~~^~~~~~~~~~~~~~~~~~~~~~
TypeError: unsupported operand type(s) for -: 'float' and 'NoneType'The 1.25 on the screen is misleading: it looks as if the discount was calculated. But print only writes the value to the screen; it does not give it to the caller. Remember from lesson 14: a function without a return returns None. On line 6, 12.5 - None is attempted; 'float' and 'NoneType' in the message says exactly this: on the left a float, on the right None. When you see NoneType in a message, the first question to ask is: which function forgot to return a value?
Now match the messages with their causes. Try it yourself before looking at the table, and go back to the table if you get stuck.
Match each message pattern with its likely cause.
For each row, pick its match from the list, then check.
ZeroDivisionError: division by zeromissing 1 required positional argument: 'qty'unsupported operand type(s) for -: 'float' and 'NoneType'cannot access local variable 'register'expected an indented block after function definitioninvalid literal for int() with base 10: 'thirty'name 'tax_amount' is not definedRecognizing messages has a reverse direction too: looking at a line and saying what will happen when it runs. Choose the result of each line below. One of them does not raise an error, be careful.
What happens when each line runs on its own?
For each row, pick its match from the list, then check.
print(totl)"85" + 5int("ten")250 / 0round(85.5, 1, 2)print("85" * 2)Two of the types in the table behave differently from the others. SyntaxError and IndentationError are caught before the program runs, while Python reads the code from beginning to end. That is why there is no Traceback line and not a single line runs. All the other types happen while the program runs, when Python reaches that line; the lines before it have done their work. Test this with a function:
What happens when this program is run?
def discount(amount): return amount * 10 / 100 print("Started")
Three errors that come with dictionary, list, and string methods (KeyError, IndexError, AttributeError) are not on this map. They will meet you with their own real messages in the lessons where you learn those structures.
The messages are in English, but a few patterns explain most cases. *is not defined*: the name has not been created. *unsupported operand type(s)*: the operation does not work with these types. *invalid literal for int()*: this string cannot be converted to an integer. *missing ... required positional argument*: a required argument is missing. *takes ... positional arguments but ... were given*: too many arguments were given. *division by zero*: you cannot divide by zero. *expected an indented block*: an indented block was expected. *cannot access local variable*: the local variable cannot be accessed (while it has no value yet).
Why is this needed? Go back to Example 1. The error happened on line 2: return revenue / sales_count. So what is wrong on this line? Nothing. The average receipt really is revenue divided by the number of sales; on Monday the same line gave the right result. The problem is not in the line but in the value that reached the line: sales_count arrived as 0. "The line where the error is shown is the wrong one" is the most common misconception. Someone acting on this misconception changes the division to a multiplication or deletes the line; the program does not crash but produces a wrong report.
The right way is to follow the value backwards. Who gave the 0 to average_receipt? One block up: day_report passed on its own sales_count parameter on line 5. Who gave the 0 to day_report? One block up: the main code wrote day_report(0, 0) on line 9. We found the source of the value. This is why the upper blocks exist in a traceback: they show the path the problem value came along.
When you find the source, the fix is one of two ways. If the value was a typing mistake (for example, if 0 was written where 8 should have been), the call is fixed. If the value is a situation that can really happen, the function handles that situation. A day when the café is closed can really happen; the number of sales being 0 is not a typing mistake, it is life itself. That is why the report should recognize this day: before going to the division, day_report asks if sales_count == 0: and returns "Average receipt: no sales". The special case is handled by day_report, not average_receipt, because the "no sales" text is a report line, and preparing the report line is the job of day_report.
First find the cause yourself:
Why did the ZeroDivisionError happen in the program in Example 1?
def average_receipt(revenue, sales_count): return revenue / sales_count def day_report(revenue, sales_count): avg = average_receipt(revenue, sales_count) return f"Average receipt: ${avg:.2f}" print(day_report(62, 8)) print(day_report(0, 0))
Now, without changing the code at all, change only the value in the call. There are three values for sales: 8, 0, and "8" in quotes. In each one, look at what remains on the screen and which lines run.
Change the sales value: how does the result change while the code stays the same?
Pick a value; predict the output first, then look.
1def average_receipt(revenue, sales_count):2 return revenue / sales_count34def day_report(revenue, sales_count):5 avg = average_receipt(revenue, sales_count)6 return f"Average receipt: ${avg:.2f}"78sales = 89print("Preparing report")10print(day_report(62, sales))
Preparing report Average receipt: $7.75
Faded lines didn't run with this value. Not a single letter of the functions changed; the only thing that changed is the value on line 8. With 8, the report is written. With 0, a ZeroDivisionError happens on line 2; with "8" (a string), a TypeError happens on the same line: an integer cannot be divided by a string. In all three cases the error is seen on line 2 but the cause is on line 8. The text Preparing report always stays on the screen, because line 9 runs before the error.
This idea holds everywhere. The line where the error happened is often innocent; the culprit is the value that came to that line from a level above.
Example 4 (case): A price that arrives as a string. The intern gave the price in quotes:
def price_with_tax(price, qty): return price * qty * 1.1 print(price_with_tax("4.25", 2))
Python's message:
OutputTraceback (most recent call last):
File "<code>", line 4, in <module>
print(price_with_tax("4.25", 2))
~~~~~~~~~~~~~~^^^^^^^^^^^
File "<code>", line 2, in price_with_tax
return price * qty * 1.1
~~~~~~~~~~~~^~~~~
TypeError: can't multiply sequence by non-int of type 'float'The error is seen on line 2, but there is nothing wrong on line 2. Look at the marks: the ^ is under the second multiplication. "4.25" * 2 does not raise an error; it puts the string next to itself twice and makes "4.254.25" (you saw this in lesson 4). Then "4.254.25" * 1.1 is requested; a string can only be multiplied by an integer, not by a float. *Sequence* in the message means string here. The cause is the "4.25" on line 4: the fix is there, by removing the quotes.
Example 5 (outside the case): Transit card. A city card app takes the balance from the screen as a string and takes $2 off for every ride:
def card_balance(balance_text, rides): balance = int(balance_text) return balance - rides * 2 print(card_balance("30", 2)) print(card_balance("thirty", 2))
What appears on the screen:
Output26
Traceback (most recent call last):
File "<code>", line 6, in <module>
print(card_balance("thirty", 2))
~~~~~~~~~~~~^^^^^^^^^^^^^
File "<code>", line 2, in card_balance
balance = int(balance_text)
ValueError: invalid literal for int() with base 10: 'thirty'The first call printed 26; the same function ran with the same line 2. In the second call, the error happened on line 2, inside card_balance, but int() was used correctly. The description shows the problem value, even in quotes: 'thirty'. This value came from the call on line 6. The fix is made in the call: the balance should be written with digits, like "30".
Let's turn these steps into a routine you will apply to every multi-level message. Put them in the right order:
You got a multi-level error message in a program with functions. Put the steps in the correct order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The fastest way to recognize messages is to break working code on purpose, as in lesson 5. This time, what you break will be inside a function; notice which function the line number in the error box falls into, and which call reached it. The receipt program you stepped through is sitting in the cell below in working order. Do three things in order; after each one, press Run, read the last line and the line number in the box, then undo the change:
1. Delete qty from the price_with_tax(price, qty) call on line 5. Which line does the box show? Which function is that line inside?
2. On line 8, write "4.25" instead of 4.25. On which line does the error appear, and on which line is the cause?
3. Replace the return on line 2 with print( (do not forget to add ) at the end of the line). What is written on the screen first, on which line is the error, and why?
Try it now· not graded; doesn't affect progress
(1) TypeError: price_with_tax() missing 1 required positional argument: 'qty', line 5: the error happens inside receipt_line, in the call itself. (2) TypeError: can't multiply sequence by non-int of type 'float', line 2: the error appears in price_with_tax, the cause is the quotes on line 8. (3) First a long number like 9.350000000000001 is printed to the screen (print writes the value without rounding), then on line 6 TypeError: unsupported format string passed to NoneType.__format__ happens: because price_with_tax now returns None, amount is empty and cannot be formatted with :.2f. When you see NoneType in a message, the first question you ask is again the same: which function forgot to return a value?
At the first meeting with a long traceback, most people start reading from the top. But the top line, Traceback (most recent call last):, is only a heading and says nothing about the problem. The first block under it is also often the call in the main code, that is, the start of the journey. The real information is at the bottom. The rule is simple: first the bottom line, then upward, the lines in your own code. In real programs, files of ready-made libraries can also appear inside the traceback; skip them and look for the lines you wrote, because the cause is often in the value you gave.
Finally, a warning: not every error gives a message. A program that multiplies instead of dividing the average receipt does not crash, it quietly writes a wrong result. These kinds of errors are called logic errors, and a traceback cannot help with them.
Because a day without sales is a situation that can really happen, we make the fix not in the call but in the day_report function that prepares the report. average_receipt did not change at all; it never reaches 0.
def average_receipt(revenue, sales_count): return revenue / sales_count def day_report(revenue, sales_count): if sales_count == 0: return "Average receipt: no sales" avg = average_receipt(revenue, sales_count) return f"Average receipt: ${avg:.2f}" print(day_report(62, 8)) print(day_report(0, 0))
OutputAverage receipt: $7.75
Average receipt: no salesThe intern had said "there are three errors"; a single if was enough. The three File blocks were the three stops of a single error.
Another attempt by the intern tries to update the global register variable from inside the function:
register = 0 def add_sale(amount): register = register + amount return register print(add_sale(4.25))
Starting to read the traceback from the top and looking for the error on the line shown. The Traceback (most recent call last): at the very top is a heading and gives no information; the first block under it is also the start of the journey. Start reading from the bottom line, and find the line where the error happened in the File block right above it. Then, before you change that line, ask: is this line correct, or did a wrong value come to it? If a value came, go up a block, find the source of the value, and make the fix there.
The bottom four lines of the message in Example 1 were these:
Output File "<code>", line 2, in average_receipt
return revenue / sales_count
~~~~~~~~^~~~~~~~~~~~~
ZeroDivisionError: division by zeroSomeone who reads from the top lingers on the Traceback heading and on line 9 in the main code; someone who looks only at the line shown thinks the return revenue / sales_count line is "broken" and changes the division. Both are heading the wrong way. The right reading: the last line says there was a division by zero, and the File block says this was on line 2 of average_receipt; the line itself is correct, because the same line produced 7.75 on Monday. When you follow the divisor 0 up the blocks, you reach the source, the day_report(0, 0) call on line 9.
File ..., line N, in name block from top to bottom: the latest call is at the bottom; the bottom block is the line where the error happened, and the ones above are the way there. A long message does not mean multiple errors.division by zero the divisor, missing ... argument the call, NoneType the function that does not return a value, cannot access local variable the assignment in the function, expected an indented block the indentation (the code never runs), invalid literal for int() the string being converted.Next lesson: Some errors give no message at all and the program quietly produces a wrong result; in the next lesson we will find them by tracing and narrowing down the problem.
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.
UnboundLocalError | cannot access local variable 'register' | Assignment to a global name inside a function | The register = ... line inside the function |
IndentationError | expected an indented block after function definition | The function body is not indented (the code never runs) | Right under the def line |
ValueError | invalid literal for int() with base 10: 'thirty' | A string that cannot be converted to a number | The value given to int() |
NameError | name 'tax_amount' is not defined | The name is wrong or written with different letters | The line where the name is defined |
Python's message:
OutputTraceback (most recent call last):
File "<code>", line 5, in <module>
print(add_sale(4.25))
~~~~~~~~^^^^^^
File "<code>", line 3, in add_sale
register = register + amount
^^^^^^^^
UnboundLocalError: cannot access local variable 'register' where it is not associated with a valueThe trap from lesson 16: because register = ... is written inside the function, Python treats register as local, and the register on the right side has no value yet. The ^^^^^^^^ mark is right under that valueless register. The solution is to take the value as a parameter and return the new one:
def add_sale(register, amount): return register + amount register = 0 register = add_sale(register, 4.25) register = add_sale(register, 2.00) print("Register:", register)
OutputRegister: 6.25In Example 5 the error was seen inside card_balance, but the function was right; writing the balance with letters was a typing mistake. So we do not touch the function, we only fix the value in the call:
def card_balance(balance_text, rides): balance = int(balance_text) return balance - rides * 2 print(card_balance("30", 2)) print(card_balance("20", 2))
Output26
16Compare with Example 6: there the value (0 sales) was a real situation and the function learned to handle it; here the value ("thirty") was a mistake and the call was fixed.