A bug is anything that makes a program behave differently from what you intended. Debugging is finding and removing bugs. Bugs come in three kinds, and telling them apart is the first step, because each needs a different approach.
Kind
When it shows up
Does Python tell you?
Example
Syntax error
Before the program starts
Yes, and nothing runs at all
a missing bracket
Exception (runtime error)
While the program is running
Yes, at the line where it happened
dividing by zero
Logic error
Never, unless you notice
No
a wrong formula
Think of giving someone directions to your home.
A syntax error is a sentence that is not proper language: "Left turn the at." They cannot even begin to follow it.
An exception is an instruction that is clear but impossible: "Drive through the wall." They follow your directions until that point, then stop.
A logic error is a perfectly clear, perfectly possible instruction that is simply wrong: "Turn left" when you meant right. They follow every step without complaint and arrive at the wrong house.
Syntax errors: Python cannot read the code
Before running anything, Python reads the whole file and checks that it follows the grammar of the language (Chapter 1 called this step parsing). If any line breaks the rules, you get a SyntaxError and not one line runs, not even the correct lines above the mistake:
File "shop.py", line 2
print("Total:", (3 + 4)
^
SyntaxError: '(' was never closed
Notice that Starting... was never printed. The first line is fine, but Python refused to start.
Exceptions: Python cannot do what you asked
If the grammar is fine, the program starts running, top to bottom. An exception is raised when a line asks for something impossible. The program stops at that line:
print("Starting...")print(10/0)print("Done")
Output
Starting...
Traceback (most recent call last):
File "shop.py", line 2, in <module>
print(10 / 0)
~~~^~~
ZeroDivisionError: division by zero
This time Starting...was printed, because that line ran before the problem. Done was not, because the program stopped at line 2. Everything a program did before the exception stays done.
No error, no warning, and an average that is higher than both marks. The code is valid and nothing impossible was asked. It just does not calculate an average: division is done before addition (Chapter 4), so this is 80 + 45. The fix is brackets: (first + second) / 2.
Python cannot catch this, because Python does not know what you meant. Only you can catch a logic error, by checking the output against an answer you already know.
Quick check
Which kind of error is each of these? (1) print("hi" (2) int("hello") (3) a program that prints the area of a rectangle as width + height.
Show the answer
Answer: (1) syntax error: the bracket is never closed. (2) exception: the code is valid, but the conversion is impossible, a ValueError. (3) logic error: it runs and gives a wrong answer.
Practice 10.1
Multiple choice
What happens when this program runs?
print("Start")print(10//0)print("Done")
The grammar of every line is correct, so the program does start.
Lines run from top to bottom. The program stops at the first line that asks for something impossible.
The answer is: It prints Start, then stops with a ZeroDivisionError
The first line runs and its output stays. Line 2 raises an exception, so the program stops there and line 3 never runs.
Multiple choice
A program runs to the end with no message, but the result is wrong. Who can catch this kind of error?
This is the third kind of error in the table of section 10.1.
Python does not know what you meant. It only knows what you wrote.
The answer is: Only you, by checking the output
A logic error is valid code that does the wrong thing. Python gives no message, so you find it by comparing the output with a result you already know.
Fix the bug
This program should print the mean of three marks. For 10, 20 and 30 it prints 40.0, which is higher than every mark. Fix the logic error.
With the replies 10 then 20 then 30, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Mean: 20.0
Output
Division is done before addition. Which part of line 4 is divided by 3 now?
Brackets decide what is calculated first. Put the whole sum inside brackets.
Traceback (most recent call last):
File "order.py", line 3, in <module>
total = price + quantity
~~~~~~^~~~~~~~~~
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Part
What it tells you
Traceback (most recent call last):
A heading: "here is how the program got to the error".
File "order.py", line 3, in <module>
Where. The file and the line number. <module> means the main part of the file, not inside a function.
total = price + quantity
The line itself, copied from your file.
~~~~~~^~~~~~~~~~
Markers under the exact part of the line that failed. The ^ points at the operator, the ~ covers the two things it was applied to.
TypeError
What kind of error: its name, also called the exception type.
unsupported operand type(s) for +: 'int' and 'str'
What went wrong, in detail: + was given an int and a str.
Read from the bottom
The most useful line is the last one. Read in this order:
The last line. What kind of error, and what is the detail?
The line number just above it. Go to that line in your file.
The markers. Which part of the line?
In the example: a TypeError, because of + between an int and a str, on line 3, at price + quantity. Now you know to ask: which of those two is a string, and why? Look up the file: quantity = "3". Found.
A traceback with several steps
When your program uses functions, which you will write in → Chapter 19, the traceback lists every call that was in progress, like a trail of breadcrumbs:
Traceback (most recent call last):
File "bill.py", line 7, in <module>
show_share(120, 0)
~~~~~~~~~~^^^^^^^^
File "bill.py", line 5, in show_share
print("Each pays:", split_bill(total, people))
~~~~~~~~~~^^^^^^^^^^^^^^^
File "bill.py", line 2, in split_bill
return total / people
~~~~~~^~~~~~~~
ZeroDivisionError: division by zero
This is why the heading says most recent call last. Read it as a story from top to bottom: line 7 called show_share, which on line 5 called split_bill, which on line 2 divided by zero. The bottom entry is where the error actually happened. The entries above it show how the program got there. In a big program, the cause is often a few steps up: here, the real mistake is passing 0 people on line 7.
Practice 10.2
Multiple choice
This program stops with a TypeError. Which line number does the traceback name?
count="4"bonus=10total=count+bonusprint(total)
The traceback names the line where Python noticed the problem, not the line where the mistake was made.
Storing text in a variable is allowed. Which line is the first one that cannot be carried out?
The answer is: Line 3
Python stops at the line with +, where text meets a number. The real mistake is earlier, on the line that stored the number as text.
10.3 A gallery of syntax errors
Syntax errors are the easiest kind to fix, because Python points straight at them. Modern Python's messages are specific, and often suggest the fix.
A string that never ends
print("Hello)
Output
File "gallery.py", line 1
print("Hello)
^
SyntaxError: unterminated string literal (detected at line 1)
A bracket that never closes
total=(3+4print(total)
Output
File "gallery.py", line 1
total = (3 + 4
^
SyntaxError: '(' was never closed
A missing comma
print("Total:" 5)
Output
File "gallery.py", line 1
print("Total:" 5)
^^^^^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?
One = where two are needed
print(5=5)
Output
File "gallery.py", line 1
print(5 = 5)
^^^
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
A space at the start of a line
print("one")print("two")
Output
File "gallery.py", line 2
print("two")
IndentationError: unexpected indent
IndentationError is a kind of syntax error. As Chapter 1 explained, the spaces at the start of a line have meaning in Python, so you cannot add them for decoration.
A missing colon. Statements such as if end their first line with a colon → Chapter 11:
age=20ifage>=18print("Welcome")
Output
File "gallery.py", line 2
if age >= 18
^
SyntaxError: expected ':'
When the message is vague
Sometimes all you get is SyntaxError: invalid syntax. Then use these facts:
Python reports the place where it became confused, which is at or just after the real mistake.
If the marked line looks perfect, look at the line above it. A missing bracket or quote on one line often only becomes a problem on the next.
Count your brackets and quotes: every opening one needs a partner. VS Code highlights the matching bracket when the cursor is next to one.
Fix only the first syntax error, then run again. One mistake can produce a confusing message, and fixing it often clears everything up.
Practice 10.3
Multiple choice
A file has two lines. Line 1 is print("one") and starts at the left edge. Line 2 is print("two") with two spaces in front of it. Which error does Python report?
Look at the start of line 2. What is there that line 1 does not have?
The spaces at the start of a line have meaning in Python. This error has its own name.
The answer is: IndentationError
Spaces at the start of a line cannot be used for decoration. Python reports an IndentationError, a kind of syntax error, and nothing runs.
Fill in the blank
Python says that a ( was never closed on line 3. The border of a rectangle is two times the sum of its width and its height. Fill in the blank with the one character that is missing.
Every ( needs a ). Where it closes matters too: the bracket must hold the whole sum so that the sum is doubled.
Fill in the blank
Fill in the blank so that the program compares the two values. With one = here, Python reports a SyntaxError.
left=5right=5.0print(left right)
The finished program prints:
Target
True
One = stores a value. A different operator asks whether two values are equal.
The error message for print(5 = 5) in this section suggests the operator.
left=5right=5.0print(left==right)
= is assignment and cannot sit inside an expression. == is the comparison, and it gives True or False.
10.4 A gallery of exceptions
There are about seventy built-in exception types. A handful account for nearly everything a beginner sees. For each one below: what it means, a typical cause, and what to check.
NameError: Python does not know that name
message="Hello"print(mesage)
Output
Traceback (most recent call last):
File "gallery.py", line 2, in <module>
print(mesage)
^^^^^^
NameError: name 'mesage' is not defined. Did you mean: 'message'?
Check: spelling, capital letters (Total and total are different names), whether you forgot quotes around text (print(hello) looks for a variable named hello), and whether the name is assigned before this line runs.
TypeError: the wrong kind of value
print("Score: "+95)
Output
Traceback (most recent call last):
File "gallery.py", line 1, in <module>
print("Score: " + 95)
~~~~~~~~~~^~~~
TypeError: can only concatenate str (not "int") to str
Check: the types of the values involved, with print(type(x)). The usual causes are text from input() that was never converted, and joining a number onto a string without str() (Chapter 6).
Another form of TypeError says something is not callable: you put brackets after a value that is not a function.
total=50print(total(2))
Output
Traceback (most recent call last):
File "gallery.py", line 2, in <module>
print(total(2))
~~~~~^^^
TypeError: 'int' object is not callable
Check: a missing operator (total(2) should be total * (2)), or a built-in name such as print, input or str that you reused as a variable (Chapter 3).
ValueError: the right type, but an impossible value
print(int("twelve"))
Output
Traceback (most recent call last):
File "gallery.py", line 1, in <module>
print(int("twelve"))
~~~^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'twelve'
int() does accept strings, so the type is fine. This particular string cannot become a number. Check: the exact text shown in quotes at the end of the message.
ZeroDivisionError: dividing by zero
students=0print(450/students)
Output
Traceback (most recent call last):
File "gallery.py", line 2, in <module>
print(450 / students)
~~~~^~~~~~~~~~
ZeroDivisionError: division by zero
It is also raised by // and %. Check: why the divisor is zero. Usually a count has not been filled in yet, or the user typed 0.
IndexError: a position that does not exist
word="cat"print(word[3])
Output
Traceback (most recent call last):
File "gallery.py", line 2, in <module>
print(word[3])
~~~~^^^
IndexError: string index out of range
Check: the length of the string against the index. Remember the last index is len(word) - 1 (Chapter 8), and that an empty string has no index 0.
AttributeError: no such method
name="maya"print(name.uper())
Output
Traceback (most recent call last):
File "gallery.py", line 2, in <module>
print(name.uper())
^^^^^^^^^
AttributeError: 'str' object has no attribute 'uper'. Did you mean '.upper' instead of '.uper'?
This site runs Python undefined. Its result for this example is a little different from the book (Python undefined).
Traceback (most recent call last):
File "gallery.py", line 2, in <module>
print(name.uper())
^^^^^^^^^
AttributeError: 'str' object has no attribute 'uper'. Did you mean: 'upper'?
Check: the spelling of the method, and the type of the value before the dot. A very common version is 'NoneType' object has no attribute ..., which means the value before the dot is None: something you expected to give back a value gave back nothing.
ModuleNotFoundError: no such module
importmaths
Output
Traceback (most recent call last):
File "gallery.py", line 1, in <module>
import maths
ModuleNotFoundError: No module named 'maths'
This uses import, which is taught in Chapter 17.
Check: the spelling (it is math), and for modules that are not part of Python itself, whether you have installed them → Chapter 43.
Two that are not your code's fault
KeyboardInterrupt appears when you press Ctrl+C to stop a running program. That is the normal way to stop a program that is stuck, for example in an endless loop → Chapter 13.
EOFError appears when input() is waiting and the input ends without anything typed, for example if you press Ctrl+Z then Enter on Windows, or Ctrl+D on macOS and Linux.
The gallery in one table
Error
In plain words
First thing to check
SyntaxError
"I cannot read this."
Brackets, quotes, colons; the line above
IndentationError
"The spaces at the start of this line are wrong."
Stray spaces; blocks lined up evenly
NameError
"I do not know this name."
Spelling, capitals, missing quotes, order of lines
TypeError
"This operation does not work on this kind of value."
type() of each value
ValueError
"Right kind of value, but I cannot use this particular one."
The actual value, with repr()
ZeroDivisionError
"You asked me to divide by zero."
Where the zero came from
IndexError
"There is nothing at that position."
The length versus the index
AttributeError
"This value has nothing by that name after the dot."
Method spelling; the type before the dot
ModuleNotFoundError
"I cannot find a module with that name."
Spelling; is it installed?
Quick check
Match each line to its error: (1) print("5" * "5") (2) print(float("five")) (3) print("hello"[10]) (4) print(lenght)
Show the answer
Answer: (1) TypeError: a string cannot be multiplied by a string. (2) ValueError. (3) IndexError. (4) NameError.
Practice 10.4
Multiple choice
Each of these four lines stops with an error. Which one stops with a ValueError?
A ValueError means: the type is fine, but this particular value cannot be used.
int() does accept strings. It cannot read every string.
The answer is: print(int("7.5"))
int() accepts text, so the type is right, but the text 7.5 is not a whole number. The other three are a TypeError, an IndexError and a NameError.
Predict the output
These three lines are the fixed forms of three errors from the gallery. What does the program print?
Python runs from top to bottom. Using a name before the line that assigns it gives a NameError.
10.5 Logic errors: the silent kind
With a logic error there is no message to read, so the question becomes: how do you even know you have one?
You know only by comparing the program's output with an answer you are sure of. That is called testing, and the simplest form needs no special tools:
Pick inputs whose correct answer you can work out in your head. The average of 80 and 90 is 85. If the program says 125, there is a bug.
Use simple numbers. 10, 100 and 0.5 make mistakes visible. With inputs like 37.2 and 81.6, you cannot tell whether the output is right.
Try the edges. Zero, one, a negative number, an empty string, a very large number. Bugs love edges.
Check whether the answer is even reasonable. An average above both numbers, a negative age, a percentage of 4000: you do not need the exact answer to know something is wrong.
Common sources of logic errors, all of which you have already met:
Cause
Example
Chapter
Precedence
first + second / 2
4
Text treated as a number
"5" + "3" giving "53"
6
= logic the wrong way round
total = price when you meant price = total
3
Integer and float division mixed up
7 // 2 when you meant 7 / 2
4
Off by one
word[len(word)], or s[0:2] for three characters
8
Comparing floats with ==
0.1 + 0.2 == 0.3
5
The or shortcut that is not one
day == "Sat" or "Sun"
5
A method result thrown away
name.upper() on its own line
9
Updating the wrong variable
count = total + 1
3
Practice 10.5
Fix the bug
This program should print the first three characters of the code. It runs with no error but prints too few characters. Fix it.
With the reply XK-42, the program prints the lines below. Your program must print exactly these lines.
Example run
XK-
Output
Test with a simple input and count the characters that come out.
A slice stops just before its second number.
code=input("Code: ")print(code[0:3])
This is an off-by-one logic error. The slice [0:2] gives the characters at index 0 and 1 only, so three characters need [0:3].
Write code
Price with tax. Ask for a price in dollars (it can be a decimal number), then for a tax rate in percent (it can be a decimal number too). Print one number: the price with the tax added, rounded to 2 decimal places. Before you trust your program, test it with easy values: a price of 100 and a rate of 10.
With the replies 100 then 10, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
To pay: 110.0
Output
Convert both replies with float() on the lines where they arrive.
The tax is a part of the price: the price times the rate, divided by 100. Add that to the price.
price=float(input("Price: "))rate=float(input("Tax rate in percent: "))total=price+price*rate/100print("To pay:",round(total,2))
The tax must be worked out from the price. price + rate / 100 runs without any message and gives a wrong result, which only a test with easy numbers reveals.
10.6 A method for fixing any bug
Random changes ("maybe if I add a bracket here...") sometimes work, teach you nothing, and often add new bugs. Use a method. It is the same one a doctor or a detective uses.
1. REPRODUCE Make the bug happen on purpose, every time.
│
2. READ Read the whole error message. Bottom line first.
│
3. LOCATE Find the first line where reality differs
│ from what you expected.
4. EXPLAIN Say exactly WHY it goes wrong, before touching anything.
│
5. FIX Make ONE small change.
│
6. TEST Run again. Fixed? Did anything else break?
│
└── not fixed? Undo the change and go back to step 3.
Some notes on the steps that people skip:
Reproduce. If the bug only appears for some inputs, find the simplest input that causes it. A bug you can trigger on demand is half solved.
Locate. This is the real work, and section 10.7 gives you the tools. The aim is to narrow the search: "the values are right at line 4 and wrong at line 9" cuts the problem in half.
Explain. If you cannot say why the fix works, you have not found the bug. You have only hidden it.
One change. Change three things at once and you will not know which one mattered, or which one broke something else.
Practice 10.6
Multiple choice
In step 5 of the method (FIX), how many changes do you make before you test again?
Look at the diagram of the six steps.
If you change several things at once, you cannot tell which change mattered.
The answer is: One
With one change at a time you always know what fixed the bug, and what broke something else.
10.7 Tools for finding the bug
Print the values
The oldest debugging tool is still the most used: add temporary print calls to see what the variables really hold.
The debug lines expose the problem at once: price is a str. Three habits make print-debugging effective:
Label every print. A bare print(x) gives you a number with no idea where it came from.
Print the type as well as the value, since 20 and "20" look the same when printed.
Remove the debug prints when you finish. A marker such as DEBUG makes them easy to find.
F-strings have a shortcut made for debugging. Put = after an expression inside the curly brackets and you get both the expression and its value. For strings it shows the repr, with quotes, so text and numbers are easy to tell apart → Chapter 16:
For logic errors, be the computer. Make a table with one column per variable and one row per line, and fill it in using what the code says, not what you meant. This is the technique from Chapter 3. Here it is on a buggy program that should swap two values:
The table shows the exact moment things go wrong: after line 3, "tea" is gone. Nothing refers to it any more, so line 4 has nothing to recover. (The correct swap is left, right = right, left.)
Cut the program in half
When you have no idea where the problem is, do not read from the top. Put one print in the middle. If the values there are right, the bug is in the second half; if they are wrong, it is in the first half. Repeat in the bad half. Each check halves the search, so even a 1000-line program needs only about ten checks.
A related trick is to comment out code. Put # in front of lines to switch them off temporarily and see whether the problem disappears.
Make the program check itself: assert
An assert statement says "I am certain this is true here. If it is not, stop immediately."
price=20quantity=3total=price*quantityasserttotal==60print("Total is correct")
Output
Total is correct
When the condition is true, assert does nothing at all. When it is false, the program stops with an AssertionError. You can add a message after a comma:
marks=105assert0<=marks<=100,"marks must be between 0 and 100"print("Marks accepted")
Output
Traceback (most recent call last):
File "check.py", line 2, in <module>
assert 0 <= marks <= 100, "marks must be between 0 and 100"
^^^^^^^^^^^^^^^^^
AssertionError: marks must be between 0 and 100
assert turns a silent logic error into a loud, early one, at the place where the bad value first appears and not twenty lines later where the damage shows. Use it for things that should never happen if your code is right. Do not use it to check what a user typed: bad user input is expected and should be handled politely, with the tool in section 10.9.
Practice 10.7
Predict the output
These debug lines show what a variable really holds. What does the program print?
The value has quotes around it, so what is its type? type() prints it in the form <class '...'>.
repr() shows a string with its quotes. Text times 2 repeats the text.
It prints
<class 'str'>
'20'
2020
The type and the repr both reveal that price is text. That explains the last line: text times a number is repeated text.
Fill in the blank
The comparison prints False for no visible reason. Fill in the blank with the function that shows the string exactly as it is, with quotes and hidden characters.
city="Lima\n"print(city=="Lima")print((city))
The finished program prints:
Target
False
'Lima\n'
A plain print(city) would hide the problem.
The section used this function on the text "Paris\n".
city="Lima\n"print(city=="Lima")print(repr(city))
repr() shows the quotes and writes the line break as \n, so the hidden character at the end becomes visible.
Multiple choice
What happens when this program runs?
stock=-2assertstock>=0,"stock must not be negative"print("Stock:",stock)
Is the condition after assert true or false for this value?
When the condition is false, the program stops at once. The error is named after the statement.
The answer is: It stops with an AssertionError
The condition is false, so assert raises an AssertionError with the message, and the last line never runs.
Put the lines in order
Put the lines in order. The program calculates a total, checks it with assert, and reports only after the check.
The program in the right order prints:
Target
Total is correct
print("Total is correct")
total=price*3
asserttotal==60
price=20
total is made from price, so price comes first.
The assert line needs total. The report must come after the check.
price=20total=price*3asserttotal==60print("Total is correct")
An assert must come after the value it checks exists, and before the lines that rely on that value being right.
Write code
One debug line. Ask for a price and do not convert the reply. Print exactly one line with one print and commas: first the label DEBUG price:, then the repr of the reply, then the type of the reply.
With the reply 20, the program prints the lines below. Your program must print exactly these lines.
Example run
DEBUG price: '20' <class 'str'>
Output
print with commas puts one space between its parts.
The three parts are the label, repr(price) and type(price).
A labelled debug line with the repr and the type shows at once that a reply from input() is text, and shows any hidden spaces too.
10.8 The debugger
Printing works, but you have to decide in advance what to print, then run, then add more prints, then run again. A debugger lets you pause a running program and look around inside it.
In VS Code
Set a breakpoint. Click in the margin just to the left of a line number. A red dot appears. A breakpoint means "pause here, before running this line".
Start debugging. Press F5 (or use the Run menu, Start Debugging) and choose Python File.
The program runs normally until it reaches the red dot, then freezes. The line about to run is highlighted.
Look. The Variables panel on the left shows every variable and its current value. Hover the mouse over a name in the code to see its value too.
Step. Use the small toolbar that appears at the top:
Button
Key
What it does
Continue
F5
run on until the next breakpoint
Step Over
F10
run this one line, then pause again
Step Into
F11
if the line calls one of your functions, go inside it
Step Out
Shift+F11
finish the current function and pause
Stop
Shift+F5
end the program
Pressing F10 again and again walks through the program one line at a time while the Variables panel updates. It is the trace table from section 10.7, filled in for you automatically. The first time you watch a variable take a value you did not expect, you have located the bug.
Without VS Code
Python has a built-in function, breakpoint(). Put it on a line of its own, and when the program reaches it, the program pauses and gives you a prompt in the terminal:
Terminal
> order.py(4)<module>()
-> total = price * quantity
(Pdb) p price
'20'
(Pdb) n
(Pdb) c
At the (Pdb) prompt, p name prints a variable, n runs the next line, c continues, and q quits. This tool is called pdb, the Python debugger, and you will use it properly in → Chapter 56.
Practice 10.8
Multiple choice
You click to the left of a line number in VS Code and a red dot appears. What does this breakpoint mean?
A breakpoint freezes the program. It does not end it.
When the program freezes, the highlighted line is the one that is about to run.
The answer is: Pause here, before running this line
The program pauses before the marked line runs. You can then look at the variables and step on with F10.
10.9 Surviving an error: a first look at try and except
So far, an exception has always ended the program. That is the right outcome for a mistake in your code: you want to see it and fix it. But some exceptions are not your mistake. If a user types abc when asked for a number, the program should not die with a traceback. It should respond sensibly.
Python lets you catch an exception with try and except:
text=input("Enter a whole number: ")try:
number=int(text)print("Twice that is",number*2)exceptValueError:
print("That was not a whole number.")print("The program carries on.")
Output
Enter a whole number: abc
That was not a whole number.
The program carries on.
Here is how to read it:
The lines indented under try: are the risky part. Python attempts them.
If one of them raises a ValueError, Python stops the try part immediately, skipping whatever was left in it, and runs the lines indented under except ValueError: instead.
If nothing goes wrong, the except part is skipped.
Either way, the program then continues with the lines after it.
The indentation (four spaces) is how Python knows which lines belong to which part. You will study indented blocks carefully in the next chapter.
With good input, the except part never runs:
text=input("Enter a whole number: ")try:
number=int(text)print("Twice that is",number*2)exceptValueError:
print("That was not a whole number.")print("The program carries on.")
Output
Enter a whole number: 21
Twice that is 42
The program carries on.
Two rules for now:
Use try/except for problems that come from outside your program and that you cannot prevent: what users type, files that may be missing, networks that may be down.
Do not use it to silence errors in your own logic. Fix those.
There is much more: catching several kinds of exception, else and finally, raising exceptions yourself, and making your own exception types. All of that is in → Chapter 41.
Practice 10.9
Predict the output
What does the program print?
text="4x"try:
number=int(text)print("Number:",number)exceptValueError:
print("Not a number")print("Done")
Can int() read the text 4x? If not, which exception is raised?
The rest of the try part is skipped. The last line is outside the block, so it always runs.
It prints
Not a number
Done
int("4x") raises a ValueError. Python skips the rest of the try part, runs the except part, and then carries on below the block.
Fill in the blank
The user types ten. Fill in the name of the exception so that the program prints its message and does not crash.
try:
hours=int(input("Hours: "))print("Minutes:",hours*60)except :
print("Please type a whole number.")
With the reply ten, the finished program prints:
Target
Please type a whole number.
Which exception does int() raise for text that is not a number?
It is the exception for the right type with an impossible value.
try:
hours=int(input("Hours: "))print("Minutes:",hours*60)exceptValueError:
print("Please type a whole number.")
int("ten") raises a ValueError. Always name the exception you expect: a bare except: would also hide your own mistakes.
Multiple choice
What happens when this program runs?
text="0"try:
print(100/int(text))exceptValueError:
print("Not a number")
int("0") works. What goes wrong one step later?
An except part catches only the exception that it names.
The answer is: It stops with a ZeroDivisionError
The conversion works, and the division by zero raises a ZeroDivisionError. The except ValueError: part does not match it, so the program still stops with a traceback.
Write code
Safe square. Ask for a whole number. Print its square alone on one line. If the reply is not a whole number, print exactly Not a whole number. and do not crash.
With the reply 7, the program prints the lines below. Your program must print exactly these lines.
Example run
49
Output
The risky line is the conversion with int(). Put it under try:.
The line that prints the square uses the number, so it belongs in the try part too. The message goes under except ValueError:.
text=input("Whole number: ")try:
number=int(text)print(number*number)exceptValueError:
print("Not a whole number.")
Bad input from a user is expected, so the program catches the ValueError and responds politely.
Fix the bug
This program should print Please type a number. when the user types a word. It still crashes with a traceback. Fix it.
With the reply two, the program prints the lines below. Your program must print exactly these lines.
Example run
Please type a number.
Output
Read the last line of the traceback. Which exception does float() really raise for a word?
The except line must name that same exception.
try:
hours=float(input("Hours: "))print("Minutes:",hours*60)exceptValueError:
print("Please type a number.")
float("two") raises a ValueError: the type, text, is fine, but the value cannot be used. An except part catches only the exception it names.
10.10 Asking for help well
Sooner or later you will be stuck on something this method does not crack, and you will ask a teacher, a friend, a forum or an AI assistant. How you ask decides whether you get help.
1. Search the last line of the error first. Copy the final line of the traceback, remove the parts specific to your program (your variable names, your file name), and search for it. Whatever your error is, thousands of people have had it before.
2. Make a minimal example. Before asking a person, shrink your program to the smallest piece of code that still shows the problem: remove everything not needed to cause the bug. Programmers call this a minimal reproducible example. About half the time, you find the bug yourself while shrinking.
3. Give the three facts. A good question contains:
Include
Example
What you expected
"I expected it to print 85.0"
What happened
"It prints 125.0", or the full traceback, copied as text
The code
The minimal example, as text, not as a photo of a screen
"It doesn't work" cannot be answered. "I expected 85.0, I get 125.0, here are the four lines" gets an answer in minutes.
4. Understand the answer. If someone hands you a fix, do not just paste it in. Work out why it fixes the problem. Otherwise you will meet the same bug again next week.
10.11 Common mistakes when debugging
The mistake
Why it hurts
Do this instead
Not reading the error message
The answer is usually in it
Read the last line, then the line number
Reading only the line number
The cause is often earlier
Ask where the bad value came from
Changing several things at once
You cannot tell what worked
One change, then test
Changing code at random
It adds new bugs
Explain the cause first
Assuming a line "must be right"
That is often exactly where the bug is
Check everything; print the values
Fixing only the symptom
The bug returns in another form
Find where the wrong value was created
Testing with only one input
Other inputs still fail
Test simple values and edge cases
Editing but not saving, or running a different file
Your changes seem to have no effect
Save first; check the file name in the traceback
Leaving debug prints in
Confusing output later
Remove them when the bug is fixed
Wrapping everything in try with a bare except
Errors vanish silently
Catch one named exception, in one place
10.12 Putting it together
10.13 How errors work inside Python
+ Practice
Questions with a Check button are checked on this page. Use the hints when you are stuck: the last step always shows the answer. The other questions show the book's answer, so that you can compare.
Questions
Check yourself
Name the three kinds of error and say when each one shows itself.
Show the answer
Syntax errors appear before the program starts. Exceptions appear while it runs, at the line that cannot be carried out. Logic errors never announce themselves; you see them only as wrong output.
Check yourself
A file has a syntax error on line 20. Do lines 1 to 19 run? Why?
Show the answer
No. Python checks the grammar of the whole file before running anything, so nothing runs.
Check yourself
A file raises an exception on line 20. Do lines 1 to 19 run? Do lines 21 onwards?
Show the answer
Lines 1 to 19 run normally. The program stops at line 20, so lines 21 onwards do not run.
Check yourself
In a traceback, which line should you read first, and what two things does it tell you?
Show the answer
The last line. It gives the type of error and a description of what went wrong.
Check yourself
Why might the line named in a traceback not be the line you need to change?
Show the answer
The traceback names the line where Python noticed the problem. The mistake may be earlier, on the line where a wrong value was created or stored.
Check yourself
What is the difference between a TypeError and a ValueError? Give an example of each using int().
Show the answer
A TypeError means the value is the wrong kind: int(None). A ValueError means the kind is acceptable but this particular value is not: int("abc").
Check yourself
Why are logic errors harder to find than the other two kinds? How do you find them?
Show the answer
Python gives no message, because the code is valid and runs. You find them by testing with inputs whose correct result you already know, and then tracing or printing values to see where they first go wrong.
Check yourself
What does print(repr(text)) show that print(text) does not?
Show the answer
The exact form of the string: quotes around it and escape sequences such as \n and \t made visible, so stray spaces and line breaks can be seen.
Check yourself
What does assert do when its condition is true? When it is false?
Show the answer
When true: nothing at all. When false: it raises AssertionError (with the message, if one was given) and the program stops.
Check yourself
In a try/except ValueError block, what happens to the remaining lines of the try part when a ValueError is raised?
Show the answer
They are skipped. Python jumps straight to the except ValueError part, then continues after the whole try/except.
Predict the output
Predict the output
print("A")print("B"+1)print("C")
Show the book's answer
A is printed, then a TypeError on line 2 stops the program. C is never printed.
print("A")print("B"+1)print("C")
Output
A
Traceback (most recent call last):
File "p1.py", line 2, in <module>
print("B" + 1)
~~~~^~~
TypeError: can only concatenate str (not "int") to str
Predict the output
print("A")print("B"
print("C")
Show the book's answer
Nothing is printed, not even A: a syntax error stops the program before it starts.
print("A")print("B"
print("C")
Output
File "p2.py", line 2
print("B"
^
SyntaxError: '(' was never closed
Is width > 0 true? When its condition is true, assert does nothing at all.
Python does exactly what line 4 says, even if that is not how the size of a rectangle is calculated.
It prints
Area: 9
The assert passes silently. The program prints Area: 9, which is a logic error: the area should be width * height, 20. The assert could not catch it, because it was checking something else.
This should print the last character of the code. It crashes.
The program prints the lines below. Your program must print exactly these lines.
Example run
2
Output
The string has 5 characters. Which index does len(code) ask for, and what is the last index that exists?
The last index is len(code) - 1. A negative index can also reach the last character.
code="XK-42"print(code[-1])
IndexError: the last index is len(code) - 1.
code="XK-42"print(code[-1])
Output
2
Fix the bug
This should print Match information as True when the user types the secret word. It prints False even when they type it correctly, because they sometimes add a space.
With the reply open , the program prints the lines below. Your program must print exactly these lines.
Example run
True
Output
print(repr(guess)) would show what the user really typed, with any space at the end.
One string method removes the spaces at both ends of the reply. Use it on the line where the reply arrives.
The program should not crash when the user types a word in place of a number. Add what is needed.
When the reply is not a whole number, print exactly Please type your age in digits, for example 20.
With the reply twenty, the program prints the lines below. Your program must print exactly these lines.
Example run
Please type your age in digits, for example 20.
Output
Which line can fail, and which exception does int() raise for the text twenty?
Put the risky lines under try: and the message under except ValueError:. The second print uses the number, so it belongs in the try part too.
try:
age=int(input("Age: "))print("In ten years you will be",age+10)exceptValueError:
print("Please type your age in digits, for example 20.")
try:
age=int(input("Age: "))print("In ten years you will be",age+10)exceptValueError:
print("Please type your age in digits, for example 20.")
Output
Age: twenty
Please type your age in digits, for example 20.
The second print is inside the try as well, because it uses age, which only exists if the conversion worked.
Coding problems
Write code · Easy
Error collector. Write five one-line programs, each of which causes a different exception from the gallery (NameError, TypeError, ValueError, ZeroDivisionError, IndexError). Run each and read the last line of its traceback.
This one is not checked automatically. Run your program, then compare it with the book's answer.
Output
Show the book's answer
One possible set, each run as a separate program:
print(score)# NameError: name 'score' is not definedprint("5"+5)# TypeError: can only concatenate str (not "int") to strprint(int("five"))# ValueError: invalid literal for int() with base 10: 'five'print(5/0)# ZeroDivisionError: division by zeroprint("five"[5])# IndexError: string index out of range
Write code · Easy
Trace it. Without running it, make a trace table for the program below and write down the final values. Then run it to check.
Finish the program with one more line that prints the final value of x first, then the final value of y.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
2 5
Output
Make one column for x, one for y and one row for each line. Fill in each row from the row above it.
On line 3 and line 5, work out the right side with the old values first. Then store the result.
x=4y=x*2x=x+yy=y-3x=x//yprint(x,y)
After line
x
y
1 x = 4
4
—
2 y = x * 2
4
8
3 x = x + y
12
8
4 y = y - 3
12
5
5 x = x // y
2
5
x=4y=x*2x=x+yy=y-3x=x//yprint(x,y)
Output
2 5
Write code · Easy
Debug prints. A program has length = "5" and width = 3, and prints length * width. Add labelled debug prints that show each value and its type, explain the output, and fix the program.
You may keep your debug prints. The check reads the last number your program prints: the correct product of length and width.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
15
Output
Print each value with a label, its repr() and its type(). Which of the two values is text?
Text times a number repeats the text. Convert length with int() before you multiply.
Safe division. Ask for two numbers and print the first divided by the second. If the second is zero, print Cannot divide by zero. and do not crash.
Convert both replies with float(). Print the label Result: and the value with a comma in print. When the second number is zero, print only Cannot divide by zero.
With the replies 10 then 4, the program prints the lines below. Your program must print exactly these lines.
Example run
Result: 2.5
Output
Only the division is risky. Put that print line under try:.
try with except ZeroDivisionError.
top=float(input("First number: "))bottom=float(input("Second number: "))try:
print("Result:",top/bottom)exceptZeroDivisionError:
print("Cannot divide by zero.")
top=float(input("First number: "))bottom=float(input("Second number: "))try:
print("Result:",top/bottom)exceptZeroDivisionError:
print("Cannot divide by zero.")
Output
First number: 10
Second number: 0
Cannot divide by zero.
Write code · Medium
Safe index. Store a word. Ask the user for a position and print the character at that position. If the position does not exist, print a friendly message.
Store the word python. Print the character alone on its line. When the position does not exist, print No such position.
With the reply 2, the program prints the lines below. Your program must print exactly these lines.
Example run
t
Output
Convert the reply with int(): an index must be a whole number.
The risky line is the one that uses the square brackets. Put it under try:.
except IndexError.
word="python"position=int(input("Position: "))try:
print(word[position])exceptIndexError:
print("No such position.")
word="python"position=int(input("Position: "))try:
print(word[position])exceptIndexError:
print(f"There is no position {position}. Use 0 to {len(word)-1}.")
Output
Position: 9
There is no position 9. Use 0 to 5.
Write code · Medium
Three bugs. The program below should print the average length of three words. It has one syntax error, one exception and one logic error. Find and fix all three, checking the final answer by hand.
Round the result to 2 decimal places when you print it.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Average length: 4.33
Output
Run it and fix one thing at a time. The syntax error shows first: count the quotes on line 3.
After the two error messages are gone, check the result by hand. How many words are there, and what does the program divide by?
Syntax error: the closing quote after planet is missing. Exception: thrid is a NameError. Logic error: there are three words, so divide by 3. Check by hand: 3 + 4 + 6 is 13, and 13 / 3 is about 4.33.
Guard with assert. Write a program that works out a percentage from scored and maximum. Add assert statements, each with a message, that stop the program if maximum is not positive or if scored is outside 0 to maximum. Test it with good values and with one bad value of each kind.
For the version you check here, use scored = 42 and maximum = 60, and print the percentage. Try the bad values on your own computer.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Percentage: 70.0
Output
An assert line has a condition, then a comma, then the message as a string.
A chained comparison such as 0 <= scored <= maximum checks both ends in one condition. Put both assert lines before the division.
scored=42maximum=60assertmaximum>0,"maximum must be positive"assert0<=scored<=maximum,"scored must be between 0 and maximum"print("Percentage:",scored/maximum*100)
scored=42maximum=60assertmaximum>0,"maximum must be positive"assert0<=scored<=maximum,"scored must be between 0 and maximum"print("Percentage:",scored/maximum*100)
Output
Percentage: 70.0
With scored = 75 the second assert stops the program:
scored=75maximum=60assertmaximum>0,"maximum must be positive"assert0<=scored<=maximum,"scored must be between 0 and maximum"print("Percentage:",scored/maximum*100)
Output
Traceback (most recent call last):
File "percent.py", line 4, in <module>
assert 0 <= scored <= maximum, "scored must be between 0 and maximum"
^^^^^^^^^^^^^^^^^^^^^^
AssertionError: scored must be between 0 and maximum
Write code · Hard
Two things can go wrong. Ask for a total amount and a number of people, and print the share per person. Catch a ValueError (not a number) with one message and a ZeroDivisionError (zero people) with a different message.
Convert the total with float() and the number of people with int(). Print Each pays: and the share with a comma in print. The two messages are Please enter numbers only. and There must be at least one person.
With the replies 90 then 4, the program prints the lines below. Your program must print exactly these lines.
Example run
Each pays: 22.5
Output
Both conversions and the division are risky, so all three lines go inside the one try part.
one try can have two except parts, one after the other.
try:
amount=float(input("Total amount: "))people=int(input("Number of people: "))print("Each pays:",amount/people)exceptValueError:
print("Please enter numbers only.")exceptZeroDivisionError:
print("There must be at least one person.")
Python uses the first except whose error type matches.
try:
amount=float(input("Total amount: "))people=int(input("Number of people: "))print("Each pays:",amount/people)exceptValueError:
print("Please enter numbers only.")exceptZeroDivisionError:
print("There must be at least one person.")
Output
Total amount: 90
Number of people: 0
There must be at least one person.
Write code · Hard
Write a bug report. Take the buggy program from E6 as it was originally written. Write the question you would post to ask for help with its first error: what you expected, what happened (the exact last line of the error), and a minimal example of at most three lines that still shows it.
This one is not checked automatically. Run your program, then compare it with the book's answer.
Output
Show the book's answer
A good report looks like this:
Expected: the program to print the average length of three words.
What happened: it does not start. The last line of the error is SyntaxError: unterminated string literal (detected at line 1).
Minimal example:third = "planetprint(len(third))
Writing it this way makes the cause obvious: with everything else removed, the missing quote is the only thing left to see.
More practice
Put the lines in order
Put the lines in order. The program asks for a number and prints its double, or a message if the reply is not a whole number. Keep the spaces at the start of the lines as they are.
With the reply 21, the program in the right order prints:
Target
42
exceptValueError:
text=input("Number: ")
try:
print("Not a whole number")
print(int(text)*2)
The reply must be stored before the try part uses it.
try: comes first with the risky line under it. except ValueError: follows with the message under it.
text=input("Number: ")try:
print(int(text)*2)exceptValueError:
print("Not a whole number")
The risky line sits under try:, and the line that responds to the problem sits under except ValueError:.
Chapter project: A marks report that survives bad input
Project
Build a small report that cannot crash on bad input. Write a program that asks four questions, in this order:
the name of a student
the first mark (a whole number)
the second mark (a whole number)
the third mark (a whole number)
Remove spaces from both ends of the name. If all three marks are whole numbers, print three lines in this exact form, each with a label and one value:
Student: and the name
Total: and the sum of the three marks
Mean: and the mean of the three marks, rounded to 1 decimal place
If any mark is not a whole number, print the line Marks must be whole numbers. in place of those three lines. In both cases, finish with the line Report finished.
Test your program the way section 10.5 says: use marks whose mean you can work out in your head, such as 10, 20 and 30, and then try a word and a decimal number as a mark.
With the replies Maya then 10 then 20 then 30, the program prints the lines below. Your program must print exactly these lines.
The three conversions with int() are the risky lines. Put them, the calculations and the three report lines under one try:. Print nothing of the report before all three marks are converted.
Under except ValueError: print the message. The line Report finished. is not indented, so it runs in both cases.
The mean is the total divided by 3. Work out the total on its own line first, then divide: that avoids the precedence mistake from section 10.1. Round only inside print.
name=input("Student: ").strip()try:
first=int(input("First mark: "))second=int(input("Second mark: "))third=int(input("Third mark: "))total=first+second+thirdmean=total/3print("Student:",name)print("Total:",total)print("Mean:",round(mean,1))exceptValueError:
print("Marks must be whole numbers.")print("Report finished.")
The program uses the ideas of the chapter together: input is cleaned and converted, the risky lines sit in one try part with a named exception, and the result is tested with easy values and with edge cases.