Using the Debugger
Have you ever gotten stuck on a problem where you're not sure what's going on? Perhaps you've been given the advice to add print statements to your code, but even after doing that, you still aren't quite sure what the problem is?
Thonny has a helpful feature called a debugger, which lets us walk through our program step-by-step to actually see what it is doing. At the top of the Thonny window, next to the run button, you will see a series of buttons that look like this:
To activate the debugger, simply click on the button that looks like a bug (the creepy-crawly kind), instead of the normal run button. When you do that, the buttons will change so that they look like this:
These buttons allow you to control the flow of the program step-by-step,
and Thonny will show you exactly what is happening by popping up a series
of function call frame windows (you can hover the mouse over each button
for a description of what it does). Note that each function call frame
window shows the values of local variables at the bottom. Also note that
if you're using Zoom, your partner will not be able to see the debugging
windows unless you are sharing your whole desktop, not just the Thonny
window. Try running the debugger with the following code (paste it into a
new file named
def innocent(a, b): return a + b def guilty(): x = 5 message = "hello" print(innocent(x, message + " world")) guilty()
The simplest way to progress is to just repeatedly click the "step into" button (the middle button with the arrow pointing between the blue lines). Doing so will show you every single step of the program. Once you get used to that, you can try the "step over" and "step out" buttons. "Step over" will execute an entire line of code without going into the detailed steps within that line, and "step out" will keep going until the end of the current function call frame. Finally, the "resume" button switches back to normal run mode and runs to the end of the program.
The last feature of the debugger is that you can double-click on a line number in the left margin of your code to create a red dot on that line called a "breakpoint." When running the debugger, even when you use the resume button, it will always stop right before each breakpoint, so this can be a quick way to observe the state of your program at specific points without having to click through each step along the way to get there. To remove a breakpoint, simply double-click the line number again.
Familiarize yourself with these features, so that the next time you run into a bug in your code, you can use them to investigate what's going on in detail.
Table of Contents
- Lab 6 Home
- Part 0: Warm up/Mini-review
- Part 1: For Loops & Lists
- Part 2: Strings and loops
- Part 3: Loops and graphics
- Extra: Using the Debugger
- Knowledge Check