Running a program in a debugger

1. What is a debugger?

When writing a program you often quickly want to check whether a piece of code executes as you expect it to do. Print statements can be used for this, but in some cases many print statements are needed to show all the information you need, which can easily become cluttered. Furthermore, print only shows you a string representation of an object. You can for example not see the difference between the integer 3 or the string "3". When debugging more complex code, a debugger can come in handy. With a debugger you can set breakpoints in your code, step forward through the code line by line and examine or even modify variables and objects live.

There exist many different Python debugger programs, but they have the same basic functionality. In this course we will be using the online debugger Python Tutor. Alternatively, for many code editors there exist python debugger packages, and some editors have a debugger built in. It is even possible to use a debugger on the command line with the built-in module pdb, although it is not the easiest interface.

2. Try it yourself!

Inspect the code of this simple guessing game in Python Tutor.

2.1 Stepping through code line by line

Anything that we define in our program (including variables, procedures/functions, etcetera) will show up on the right side. Note that Python Tutor shows some terms that we have not (yet) discussed in this course (e.g., objects and frames), it is not essential right now to understand all of these terms.

In this case, we can find the module that is imported and the two functions (procedures) that are defined.

Global frame

Afterwards we enter the first procedure start_game() which subsequently calls guess_number(). On the right side of the screen you can see the procedures being called (in the order in which they are being called), and the variables that are defined inside these procedures.

Local frame

Note that when we ask the user to fill in a number using input, this number is stored as a string named user_guess. This string is then cast to an integer named user_guess_int. The difference between the integer and string can easily be identified by the quotation marks.

3 Some final notes