Ben Forta
This is a bonus chapter that didn't fit in the printed book. It's here online for you to read, download, and print as you see fit.

Chapter 25

Tinkering, Testing, and Debugging Revisited

We're friends. So, between us friends, we have a confession to make.

Our book Captain Code — it's pretty cool, right? Yeah, we think so, too. But, and this is embarrassing to admit, there's a problem with it. It's not quite perfect. Why? We had so much we wanted to share with you that we ran out of space! Seriously! Oh, the horror!

So, what to do? Well, we came up with a solution. One more bonus chapter, right here online, for you to read, download, print, as you see fit. Here goes!

Tinkering Made Easy

As you've learned in our 24 chapters together, coding is all about creative problem solving, breaking down problems into smaller bite sized chunks, and smartly using the resources available to you to solve those problems.

And those resources? There are lots of them. The standard Python installation comes with 200 or so libraries and thousands of functions and methods. On top of that, there are over 100,000 3rd party libraries available, too. You're not going to remember every single detail of every single method. Nor should you. After all, you have documentation and Google at your disposal!

And you are going to want to tinker. Lots. One way to do this is to create test programs which print results when executed. But Python provides another super fun and easy way to test code.

We'd like to introduce you <drumroll please> to the Python interpreter. Here's what you need to do:

  1. In Visual Studio Code open a terminal window. If needed, open the Terminal menu and click on New Terminal.
  2. At the command prompt in the Terminal window, type the following:
    Windows:python
    Mac:python3
  3. You'll see Python version information displayed, followed by a >>> prompt, like this:
Python interpreter prompt
  1. You can now type Python commands after the >>> prompt.
  2. When done, type exit() to exit the Python interpreter.

Ok, so what can we do in the interpreter? Honestly, anything you can do in a single Python file. Launch the Python interpreter and then type the following:

print("Hello from the Python interpreter")

Then press Enter to execute the print() statement. You'll see the results displayed right away, like this:

Python interpreter output

The Python interpreter is a great place to experiment with variables. For example, you could create a list:

fruit=["apple","pear","orange","kiwi"]

You can then work with the variable as needed:

print(fruit)
print(len(fruit))
print(fruit[2])

You can also import libraries right within the interpreter:

import random
print(random.randrange(1,101))

Oh, and here's a fun tip. Within the interpreter you can use your keyboard's arrow up and arrow down keys to display previous lines of code, find the one you want, edit it if needed, and press Enter to execute.

The Debugger

As much as we'd like all of our code to work perfectly, debugging is a fact of life for us coders. How did we debug our code throughout the book? By sticking temporary print() statements right within code. But there's another way.

Using Visual Studio's powerful interactive debugger, you can execute your code line by line and see exactly what's going on under the hood. And as Visual Studio supports all sorts of languages, the Debugger supports them too — so once you learn to use it with Python, you'll know how to use it with any language.

Here is a program that generates 10 unique random numbers. Copy the code and save it.

# Generate 10 unique random numbers
# Import
import random
# List to store results
numbers = []
# Loop until we have 10 numbers
while numbers.count(10) < 10:
    # Generate a random number
    num=random.randrange(1,101)
    # Do we have this one already?
    if not num in numbers:
        # No, so add it to the list
        numbers.append(num)
# Display the numbers
print(numbers)

You can try running it if you'd like. But, be warned, there's something horribly wrong with it — it displays nothing at all, even though it seems to run forever. This is the dreaded infinite loop! Let's use the Debugger to find out why.

Accessing the Debugger

VS Code Debugger icon

To use the Debugger, switch to the Debugger screen. Look at the icons on the top left of Visual Studio. Click on the Debugger icon — it looks like an Execute triangle with a bug on it, shown here on the right. You can click this icon any time to go to the Debugger screen. To get back to the usual Explorer view, just click the top icon.

So, click the Debugger icon. You should see a screen like this:

VS Code Debugger screen

Setting Breakpoints

The magic of interactive debuggers is that they allow you to run your code line by line, pausing after each so you can look at code processing paths, variable values, and more. You tell the Debugger where to pause using Breakpoints.

Find the line of code with the while loop (line 10). Move your mouse to the left of the line number — you'll see a dark red circle. Click it and it turns bright red. That's it, you've created a breakpoint. Here's what the screen will look like:

Debugger breakpoint set

Starting the Debugger

When you open the Debugger screen, you may see a prompt like this:

Run and Debug button

If this happens, click the blue Run and Debug button. You may then be prompted with options like this:

Debug configuration selector

Select Python File and the Debugger will start. If VS Code didn't show that prompt, just click the green Start Debugging button at the top left of the screen.

A Tour of the Debugger

Now you have the Debugger open. Here's what the screen looks like:

VS Code Debugger overview

There are just a few things you really need to pay attention to for now:

  • Your code is on the upper right. A colored bar indicates the line the Debugger stopped at.
  • The VARIABLES window on the left shows all variables and their values as you step through your code.
  • The WATCH window lets you type Python expressions to watch.
  • The CALL STACK window shows where you are within the program.
  • Debugger toolbar Above the editor window is this toolbar with six buttons used to control debugging.
  • Execute button Above the VARIABLES window is a green Execute button that executes your code in the Debugger.

Stepping Through Code

Your program is now paused in the debugger. Use the toolbar buttons:

  • Step Into (3rd button) — advances one line at a time.
  • Step Out (4th button) — steps out of the current block.
  • Continue (1st button) — runs until the next breakpoint.
  • Stop (last button, red square) — stops the Debugger session.

Inspecting Variables

Variables window

The VARIABLES window shows variables as they change. As you step through our program, you'll see numbers growing by one value each time the while loop iterates, something like this.

Actually, if you double-click on a variable in this window, you can even edit the value! Keep that in mind for future debugging.

Hovering over variable

You can also see variable values just by mousing over them in your code. Hover over num and you'll see the last value it was set to.

Keep clicking Continue. Each time the Debugger stops, look at numbers in the Variables window. Keep clicking until there are more than 10 values — lots more. Well, I guess we know why the program ran forever.

Watching Expressions

The WATCH window lets you enter expressions and see their results. Click the + to add this expression:

numbers.count(10)
Watch window showing count

That's the same expression we're using in our while. It evaluates to 0 and never changes. Click Continue a few times — does this expression change? Nope.

We used the wrong function! count() returns the number of list items with a specific value — passing 10 means it only counts how many times the number 10 appears. That's the dreaded infinite loop!

The function we should have used is len(). Add another expression to test it:

len(numbers)
Watch window showing len

Now use Continue to keep running. The WATCH window shows that len() is indeed returning the value we need. That's what we should have used as our while condition. Whew, thankfully that's an easy fix!

Ending Debugging

Before editing your code, always stop the Debugger first by clicking the Stop button (red square on the toolbar). If you just go back to edit your code the Debugger will still be running in the background — we don't want that.

Fix the while loop so that it looks like this:

while len(numbers) < 10:

Save the code, run it, make sure the bug has been fixed.

Summary

In this bonus chapter we showed you two important goodies that are critical parts of any coding superhero's bag of tricks. We started with the Python interpreter which provides a wonderful way to tinker and play with functions, expressions, and more. And then we used the powerful Interactive Debugger to step through code while it is executing. And with that Captain Code can make an impressive exit, never to be seen again. Well, just until the sequel.