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 this page on Colab

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:

  • main calls the other functions. Programs often have a function with this name, which the last line calls.

  • print_table displays a multiplication table. It has a nested loop: a while loop in the body of another while loop (“11b. Additions: While Loops”). It calls multiply.

  • find_right_triangles finds the right triangles whose sides are whole numbers up to limit: the numbers a, b and c with a * a + b * b == c * c (Pythagoras). It has a doubly nested loop: a for loop in a for loop in a for loop, three levels. It calls is_right_triangle.

  • multiply and is_right_triangle are 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#

  1. Click View, then Variables. The Variables area shows the variables of the program and their values.

  2. 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:

  • col goes 1, 2, 3, 4, 5 while row stays 1. The inner body runs for col equal to 1 to 4.

  • When col is 5, the inner condition is false. The box goes to print(), then to row = row + 1.

  • Then col = 1 runs 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:

  1. Copy the code into a new file in Thonny, and start the debugger.

  2. Step into print_table(3), and press Step over until the first row is displayed.

  3. Look at the Variables area when row becomes 2: col is still 4. The inner condition col <= size is false, so the inner body does not run for the second row.

  4. The cause: nothing sets col back to 1. The line col = 1 is 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.

  1. You want to see the lines of print_table run, one at a time. Which command do you use?

  2. You trust print_table, and you want to go on to the next line of main. Which command do you use?

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?

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)

Hide code cell output

1 2 3 
2 4 6 
3 6 9 

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.

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

Hide code cell output

[(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15), (12, 16, 20)]

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

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):
    ...

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