Debugging in VS Code

We will assume that we're using Python for these examples.

Switch to the Directory Containing the Code File

You can open a code file by double clicking it, but VS Code functions better if you open the directory containing the file.

Switch to the Correct Directory

If prompted about whether you trust the workspace, click "Yes".

Be aware of where your files are saved! If your computer is saving to the cloud (OneDrive, Google Drive, etc.), you may not be able to debug the files.

Begin Debugging

Find the Debug icon (looks like a bug) in the Activity Bar on the left side of the screen. Click on it.

Start Debugging

Then click on the green play button.

Note: there is another play button in the upper right corner of the screen. For consistency I recommend using the one in the Activity Bar.

Start Debugging

You may then be prompted from the top bar once or twice to select the Python interpreter and choose the current file. Both times chose the default (topmost) option.

If it worked you should see any output in the terminal, something like this:

mpjovanovich:  cd /home/mpjovanovich/tmp ; /usr/bin/env /bin/python3 ...
8

Breakpoints

The real power of debugging comes from setting breakpoints. These stop the execution of the program at specific lines and allow you to see the values of variables. You can then step through the code one line at a time to see how it executes.

To do this click in the margin to the left of the line you want to set the breakpoint on. A red dot should appear.

Breakpoint

When starting out, it's often best to set the breakpoint on the first line that isn't a comment.

Stepping Through Code

After setting a breakpoint and starting the debugger you should see the program halt at the breakpoint, and a new toolbar should appear at the top with several buttons.

Debug Toolbar

The option descriptions can be seen by hovering over the buttons.

Watching Variables

Being able to see the values of variables as the program runs is extremely useful.

There are several places to check these values:

Watch Variables

Hovering (Tool Tip)

Hovering over a variable will show you its value at that point in the program.

Variables View

All variables in scope are shown here.

Watch View

You can add your own custom expressions to watch by either:

This is useful for watching "subexpressions" that are part of a larger expression.