11c. Additions: The Thonny Debugger#
Additions to Chapter 11: Tuples: how to use the debugger of Thonny to run a program one step at a time, and to see the value of each variable at each step. The page gives a program to practice with: functions that call other functions, a nested loop, and a doubly nested loop. Read this page after “11b. Additions: While Loops”. The practice questions at the end have answers: try each question first, then open its Answer.
Run the setup cell below first. It downloads thinkpython.py, the helper module the chapters use.
from os.path import basename, exists
def download(url):
filename = basename(url)
if not exists(filename):
from urllib.request import urlretrieve
local, _ = urlretrieve(url, filename)
print("Downloaded " + str(local))
return filename
download('https://github.com/AllenDowney/ThinkPython/raw/v3/thinkpython.py');
import thinkpython
What a debugger does#
A debugger is a tool that runs a program one step at a time. After each step, it stops and shows:
which part of the code runs next;
the value of each variable;
which functions were called, and which function called which.
With a debugger you do not need to guess what a program does: you watch it. It is the best tool to find a bug in a loop or in a function, and to understand code that someone else wrote. Chapter 3 shows stack diagrams on paper; the debugger shows the same information while the program runs.
The debugger is part of Thonny, the program for writing and running Python that we use in class. Colab does not have a debugger like this one. To install Thonny, and to learn the two parts of its window (the editor at the top, the Shell at the bottom), read Another Note From Prof. Rosenthal: Using Thonny. “3c. Additions: More About for Loops” shows a first, short example of the debugger.
The program to practice with#
This program has five functions:
maincalls the other functions. Programs often have a function with this name, which the last line calls.print_tabledisplays a multiplication table. It has a nested loop: awhileloop in the body of anotherwhileloop (“11b. Additions: While Loops”). It callsmultiply.find_right_trianglesfinds the right triangles whose sides are whole numbers up tolimit: the numbersa,bandcwitha * a + b * b == c * c(Pythagoras). It has a doubly nested loop: aforloop in aforloop in aforloop, three levels. It callsis_right_triangle.multiplyandis_right_triangleare small functions. They are here so that you can practice going into a function call and out of it.
So there are three levels of calls: main calls print_table, which calls multiply. Run the cell to see
what the program displays:
# debug_demo.py: a program to practice with the Thonny debugger
def multiply(a, b):
product = a * b
return product
def print_table(size):
row = 1
while row <= size: # outer loop
col = 1
while col <= size: # inner loop (a nested loop)
print(multiply(row, col), end='\t')
col = col + 1
print()
row = row + 1
def is_right_triangle(a, b, c):
return a * a + b * b == c * c
def find_right_triangles(limit):
found = []
for a in range(1, limit + 1): # outer loop
for b in range(a, limit + 1): # middle loop
for c in range(b, limit + 1): # inner loop (a doubly nested loop)
if is_right_triangle(a, b, c):
found.append((a, b, c))
return found
def main():
print('A multiplication table:')
print_table(4)
print()
triangles = find_right_triangles(15)
print('Right triangles with whole-number sides up to 15:')
for triangle in triangles:
print(triangle)
main()
A multiplication table:
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
Right triangles with whole-number sides up to 15:
(3, 4, 5)
(5, 12, 13)
(6, 8, 10)
(9, 12, 15)
'\t' is the tab character: end='\t' puts a tab after each number instead of a newline, so the
numbers of a row line up in columns. Each tuple, such as (3, 4, 5), is one right triangle.
Copy the program into Thonny. On the website, point to the code cell and click the copy button at its top
right (in Colab, select the code and copy it). In Thonny, click File, then New, paste the code in the
editor, and save the file as debug_demo.py. Press F5 (or click the green Run button) to run it
once: the Shell shows the same output as above.
Start the debugger#
Click View, then Variables. The Variables area shows the variables of the program and their values.
Click the Debug button (the picture of a bug, next to the Run button), or press Ctrl+F5 (Run, then Debug current script (nicer)).
Thonny starts the program, and stops before the first line. A box (a highlighted area) shows the part of the code that runs next. The program waits for you: each step command below runs a part of the code, and stops again.
Command |
Key |
What it does |
|---|---|---|
Step over |
F6 |
Runs the part in the box completely, also any function that it calls, and stops at the next part. |
Step into |
F7 |
Goes into the part in the box: into the parts of an expression, one at a time, or into the code of a function that it calls. |
Step out |
(no key) |
Runs the rest of the current function, and stops after it returns. |
Resume |
F8 |
Runs the program until the next breakpoint, or to its end. |
Run to cursor |
Ctrl+F8 |
Runs the program until it gets to the line where the cursor is. |
Step back |
Ctrl+B |
Goes back one step, to see what happened before (only in the nicer debugger, below). |
Stop |
Ctrl+F2 |
Stops the program. |
The commands are in the Run menu too, and the main ones have buttons in the toolbar: Over, Into, Out, Resume and the red Stop. On a Mac, the keys F5 to F8 can control the screen or the sound: hold down the fn key, or use the buttons. On a Mac, Step back is Command+B.
Step over or Step into? Use Step over for a line that you trust, for example a call of print, or
a function that you know works. Use Step into to see how a line runs. On an expression, Step into shows
how Python evaluates it: Thonny replaces each part with its value, one at a time. For example, in multiply,
the expression a * b becomes 2 * 3, and then 6.
A tour of the program#
Do these steps in Thonny, and look at the Variables area after each step.
1. The definitions. The box is on def multiply(a, b):. Press Step over until the box is on the
last line, main(). Each def statement only defines a function: it does not run the body. After each
def, the Variables area shows one more function name.
2. Into main. Do not press Step over on main(): it would run the whole program at once. Press
Step into until Thonny opens a new small window with the code of main. Each function call gets its own
window, with its own box and its own local variables: this is the frame of the call. (If Thonny shows the
call in the editor instead, click Tools, Options, Run & Debug, and select “Show function calls
(frames) in separate windows”.) Press Step over once: the Shell displays A multiplication table:.
3. Into print_table: the nested loop. The box is on print_table(4). Press Step into until the
window of print_table opens. Now press Step over many times, and watch row and col:
colgoes 1, 2, 3, 4, 5 whilerowstays 1. The inner body runs forcolequal to 1 to 4.When
colis5, the inner condition is false. The box goes toprint(), then torow = row + 1.Then
col = 1runs again: the inner loop starts again for the next row. This is the line that the most common mistake leaves out of the outer body (see “Find a bug with the debugger” below).
4. Into multiply, and out again. When the box is on the line print(multiply(row, col), end='\t'),
press Step into until the window of multiply opens. Its local variables are a and b, with the
values of row and col. Press Step out: the call returns, its window closes, and you are back in
print_table.
5. The stack. If the Stack area is not open, click View, then Stack. The Stack area lists the calls that have not returned yet,
in order: the module (the program itself), main, print_table, and, while it runs, multiply. Click a line
of the list to see the variables of that call.
6. Out of print_table. Press Step out. The rest of the table runs, and the box goes back to main.
Breakpoints: stop at one line#
find_right_triangles(15) runs its inner body 680 times: too many steps to press Step over for each one. A
breakpoint tells the debugger where to stop.
7. Set a breakpoint. In the editor window of debug_demo.py, click the line number at the left of the
line found.append((a, b, c)). Thonny marks the line. (Click the line number again to remove the breakpoint.)
8. Resume. Press Resume (F8). The program runs without stopping until it gets to the breakpoint:
the first time that is_right_triangle returns True. Look at the Variables area of the window of
find_right_triangles: a is 3, b is 4, c is 5, and found is still the empty list [], because
the line in the box has not run yet.
9. Resume again. Press Resume again. Each time, the program stops at the next right triangle, and
found has one more tuple. The program stops 4 times in all: at (3, 4, 5), (5, 12, 13), (6, 8, 10) and
(9, 12, 15). Watch the order in which a, b and c change: c changes fastest (the inner loop), and a
slowest (the outer loop).
10. The end. Remove the breakpoint, and press Resume. The program runs to its end, and the Shell shows the rest of the output.
Run to cursor is a breakpoint for one time only: click in a line to put the cursor there, and press Ctrl+F8. The program runs until it gets to that line.
The two debuggers of Thonny#
Thonny has two debuggers, both in the Run menu:
Debug current script (nicer), Ctrl+F5, the one that the Debug button uses. It stops at each part of each line, and it shows how Python evaluates each expression. Use it to learn what a line does.
Debug current script (faster), Shift+F5. It stops only at each line, and it runs much faster between breakpoints. Use it for programs with many iterations.
The step commands work the same way in both.
After the program ends, the Shell still knows the functions of the program. Type a call at the >>>
prompt to test one function on its own, for example is_right_triangle(6, 8, 10) or print_table(2).
Find a bug with the debugger#
This version of print_table has a bug. It displays only the first row of the table, and empty lines:
def print_table(size):
row = 1
col = 1
while row <= size:
while col <= size:
print(row * col, end='\t')
col = col + 1
print()
row = row + 1
print_table(3)
1 2 3
To find the bug with the debugger:
Copy the code into a new file in Thonny, and start the debugger.
Step into
print_table(3), and press Step over until the first row is displayed.Look at the Variables area when
rowbecomes2:colis still4. The inner conditioncol <= sizeis false, so the inner body does not run for the second row.The cause: nothing sets
colback to1. The linecol = 1is before the outer loop, so it runs only once.
The fix: move col = 1 into the body of the outer loop, right before the inner loop, as in debug_demo.py.
“11b. Additions: While Loops”, “Nested while loops”, explains this rule.
Practice questions#
Question 1 (easy): which command?#
You debug debug_demo.py. The box is on the line print_table(4) in main.
You want to see the lines of
print_tablerun, one at a time. Which command do you use?You trust
print_table, and you want to go on to the next line ofmain. Which command do you use?
Answer
Step into (F7): it goes into the call, and Thonny opens a window for
print_table.Step over (F6): it runs the whole call of
print_table, and stops at the next line ofmain.
Question 2 (easy): what went wrong?#
A student starts the debugger on debug_demo.py and presses Step over again and again. After one of
the steps, the whole program has run, and the Shell shows all of its output. Which line was in the box at
that step, and why did the whole program run?
Answer
The box was on the last line, main(). (The steps before it ran the def statements, which only define
the functions.) Step over runs a function call completely, so it ran all of main, and with it the whole
program. To go into main, use Step into on the line main().
Question 3 (medium): what is displayed?#
Predict what this code displays. Then run the cell to check (on the website, click Show code cell output).
def multiply(a, b):
product = a * b
return product
def print_table(size):
row = 1
while row <= size:
col = 1
while col <= size:
print(multiply(row, col), end=' ')
col = col + 1
print()
row = row + 1
print_table(3)
Answer
1 2 3
2 4 6
3 6 9
The outer loop goes through the rows 1 to 3. For each row, the inner loop goes through the columns 1 to 3,
and displays row * col, with a space after it. print() ends each row.
Question 4 (medium): how many times?#
How many times does find_right_triangles(3) call is_right_triangle? (Hint: b starts at a, and c
starts at b. List the values of a, b and c.) Use the debugger to check: set a breakpoint on the line
if is_right_triangle(a, b, c):, call find_right_triangles(3), and count how many times the program stops.
Answer
10 times. The loops give each a, b and c from 1 to 3 with a <= b <= c:
|
|
values of |
calls |
|---|---|---|---|
1 |
1 |
1, 2, 3 |
3 |
1 |
2 |
2, 3 |
2 |
1 |
3 |
3 |
1 |
2 |
2 |
2, 3 |
2 |
2 |
3 |
3 |
1 |
3 |
3 |
3 |
1 |
3 + 2 + 1 + 2 + 1 + 1 = 10. None of them is a right triangle, so the function returns [].
Question 5 (medium): a breakpoint#
In debug_demo.py, main calls find_right_triangles(20) instead of find_right_triangles(15). There is a
breakpoint on the line found.append((a, b, c)), and you press Resume again and again. How many times
does the program stop at the breakpoint? What are the values of a, b and c the last time? Run the cell
to check (on the website, click Show code cell output).
def is_right_triangle(a, b, c):
return a * a + b * b == c * c
def find_right_triangles(limit):
found = []
for a in range(1, limit + 1):
for b in range(a, limit + 1):
for c in range(b, limit + 1):
if is_right_triangle(a, b, c):
found.append((a, b, c))
return found
print(find_right_triangles(20))
Answer
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15), (12, 16, 20)]
The program stops 6 times: once for each right triangle, before it is added to the list. The last time, a
is 12, b is 16 and c is 20. The triangles are found in the order of a (the outer loop), so
(8, 15, 17) comes before (9, 12, 15).
Question 6 (hard): find the bug#
This function is supposed to count the pairs of whole numbers a and b with 1 <= a < b <= limit. For
limit equal to 4, there are 6 such pairs: (1, 2), (1, 3), (1, 4), (2, 3), (2, 4) and (3, 4). But
count_pairs(4) returns 3. Run the code in the Thonny debugger, watch a and b, and find the bug. Then
fix it.
def count_pairs(limit):
count = 0
a = 1
b = a + 1
while a <= limit:
while b <= limit:
count = count + 1
b = b + 1
a = a + 1
return count
count_pairs(4)
3
Answer
In the debugger, b goes 2, 3, 4, 5 while a is 1, and the count becomes 3. When a becomes 2, b is
still 5, so the inner loop never runs again. The line b = a + 1 is before the outer loop: it runs only
once. Move it into the outer body, right before the inner loop, so that b starts at a + 1 for each a:
def count_pairs(limit):
count = 0
a = 1
while a <= limit:
b = a + 1
while b <= limit:
count = count + 1
b = b + 1
a = a + 1
return count
Now count_pairs(4) returns 6.
Question 7 (hard): write a function#
Write a function called count_three_sums that takes a whole number n and returns how many ways there are
to write n as a sum a + b + c of three whole numbers with 1 <= a <= b <= c. Use a doubly nested loop
(three loops), as find_right_triangles does. Then watch it in the Thonny debugger with a small n.
For example, count_three_sums(6) returns 3 (1 + 1 + 4, 1 + 2 + 3 and 2 + 2 + 2), count_three_sums(9)
returns 7, and count_three_sums(2) returns 0.
Start from this header (replace ... with the body):
def count_three_sums(n):
...
Answer
def count_three_sums(n):
count = 0
for a in range(1, n + 1):
for b in range(a, n + 1):
for c in range(b, n + 1):
if a + b + c == n:
count = count + 1
return count
As in find_right_triangles, b starts at a and c starts at b, so each sum is counted once, in the
order a <= b <= c. The innermost body checks each choice of a, b and c, and counts the ones whose sum
is n.
Credits#
Additions by Prof. Y. Rosenthal, for Think Python: 3rd Edition by Allen B. Downey. Text license: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International