Core by Critic
ChaptersStreak: 0 days

Ultimate Core Python · Chapter 10

Errors and Debugging

This lesson goes with Episode 10 of the Ultimate Core Python course on the Core by Critic channel on YouTube.

0 of 0 done

10.1 Three kinds of error

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:

print("Starting...")
print("Total:", (3 + 4)
print("Done")

Output

  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.

Logic errors: Python does exactly what you said

first = 80
second = 90
average = first + second / 2
print("Average:", average)

Output

Average: 125.0

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")
Choose one answer

Multiple choice

A program runs to the end with no message, but the result is wrong. Who can catch this kind of error?

Choose one answer

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

10.2 Reading a traceback

When an exception stops a program, Python prints a report called a traceback. Here is one, with every part labelled:

price = 20
quantity = "3"
total = price + quantity
print(total)

Output

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:

  1. The last line. What kind of error, and what is the detail?
  2. The line number just above it. Go to that line in your file.
  3. 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:

def split_bill(total, people):
    return total / people

def show_share(total, people):
    print("Each pays:", split_bill(total, people))

show_share(120, 0)

Output

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 = 10
total = count + bonus
print(total)
Choose one answer

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 + 4
print(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 = 20
if age >= 18
    print("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?

Choose one answer

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.

width = 6
height = 4
border = (width + height * 2
print("Border:", border)

The finished program prints:

Target

Border: 20

Fill in the blank

Fill in the blank so that the program compares the two values. With one = here, Python reports a SyntaxError.

left = 5
right = 5.0
print(left  right)

The finished program prints:

Target

True

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 = 50
print(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 = 0
print(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

import maths

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?

Choose one answer

Predict the output

These three lines are the fixed forms of three errors from the gallery. What does the program print?

word = "cat"
print(word[len(word) - 1])
print(int(" 12 ") + 1)
print("Score: " + str(95))

Fix the bug

This program stops with an AttributeError. Fix it so that it prints the city in capital letters.

With the reply tokyo, the program prints the lines below. Your program must print exactly these lines.

Example run

Welcome to TOKYO

Put the lines in order

Put the lines in order so that no line causes a NameError.

The program in the right order prints:

Target

Total: 10.0
  1. tax = price * 0.25
  2. total = price + tax
  3. print("Total:", total)
  4. price = 8

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:

  1. 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.
  2. 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.
  3. Try the edges. Zero, one, a negative number, an empty string, a very large number. Bugs love edges.
  4. 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-

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

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?

Choose one answer

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.

price = "20"
quantity = 3
print("DEBUG price:", price, type(price))
print("DEBUG quantity:", quantity, type(quantity))
total = price * quantity
print("Total:", total)

Output

DEBUG price: 20 <class 'str'>
DEBUG quantity: 3 <class 'int'>
Total: 202020

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:

price = "20"
quantity = 3
print(f"{price=} {quantity=} {price * quantity=}")

Output

price='20' quantity=3 price * quantity='202020'

Reveal invisible characters with repr

From Chapter 7: when a string comparison fails for no visible reason, print the repr.

answer = "Paris\n"
print(answer == "Paris")
print(repr(answer))

Output

False
'Paris\n'

Trace by hand

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:

left = "tea"
right = "coffee"
left = right
right = left
print(left, right)

Output

coffee coffee
After line left right
1 "tea" —
2 "tea" "coffee"
3 left = right "coffee" "coffee"
4 right = left "coffee" "coffee"

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 = 20
quantity = 3
total = price * quantity
assert total == 60
print("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 = 105
assert 0 <= 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?

price = "20"
print(type(price))
print(repr(price))
print(price * 2)

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'

Multiple choice

What happens when this program runs?

stock = -2
assert stock >= 0, "stock must not be negative"
print("Stock:", stock)
Choose one answer

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
  1. print("Total is correct")
  2. total = price * 3
  3. assert total == 60
  4. price = 20

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'>

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

  1. 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".
  2. Start debugging. Press F5 (or use the Run menu, Start Debugging) and choose Python File.
  3. The program runs normally until it reaches the red dot, then freezes. The line about to run is highlighted.
  4. 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.
  5. 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?

Choose one answer

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)
except ValueError:
    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)
except ValueError:
    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)
except ValueError:
    print("Not a number")
print("Done")

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.

Multiple choice

What happens when this program runs?

text = "0"
try:
    print(100 / int(text))
except ValueError:
    print("Not a number")
Choose one answer

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

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.

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

Predict the output

value = "12"
try:
    print(int(value) + 1)
    print(int("x" + value))
    print("after")
except ValueError:
    print("caught")
print("end")

Predict the output

width = 4
height = 5
assert width > 0
area = width + height
print("Area:", area)

Fix the bug

Fix the bug

Name the kind of error and fix it.

The program prints the lines below. Your program must print exactly these lines.

Example run

Welcome to Tokyo

Fix the bug

Name the kind of error and fix it.

The program prints the lines below. Your program must print exactly these lines.

Example run

Price: 5.0 Quantity: 3

Fix the bug

This should print the price with 20% tax added. For a price of 50 it prints 50.2.

The program prints the lines below. Your program must print exactly these lines.

Example run

60.0

Fix the bug

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

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

Fix the bug

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.

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.

Show the book's answer

One possible set, each run as a separate program:

print(score)            # NameError: name 'score' is not defined
print("5" + 5)          # TypeError: can only concatenate str (not "int") to str
print(int("five"))      # ValueError: invalid literal for int() with base 10: 'five'
print(5 / 0)            # ZeroDivisionError: division by zero
print("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

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

Write code · Medium

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

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

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

Write code · Hard

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

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

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.

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 = "planet print(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
  1. except ValueError:
  2. text = input("Number: ")
  3. try:
  4. print("Not a whole number")
  5. print(int(text) * 2)

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:

  1. the name of a student
  2. the first mark (a whole number)
  3. the second mark (a whole number)
  4. 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.

Example run

Student: Maya
Total: 60
Mean: 20.0
Report finished.