The Debugger (in VS Code)

Our programs have grown in size since Week 1, and you're now seeing errors in your programs that are more difficult to fix. Much of the difficulty now comes from losing track of how your program is executing and what values are in which variables at any given point in time. Today we introduce you to a very helpful tool: the python debugger. Your VS Code installation already has it ready to use.

Reading

Overview of the Python Debugger on the Web. Jump to Let's start debugging. If you attended class and paid attention, then this reading is not required. Perhaps you can bookmark it for later reference.

Today in Class

  1. Using print() for debugging, pros and cons
  2. What is a debugger?
  3. Introduction to VS Code's debugger
  4. Breakpoints, Continue, Step
  5. Conditional Breakpoints
  6. A couple use cases

You should be able to DEBUG these programs.

The following function is from an early version of our recent homework. It incorrectly returned TRUE for the number 4. Can you see why? Use the debugger! Find the bug!

def isprime(num):
    """ This returns True if the given int is prime, and False otherwise. """
    if num <= 1:
        return False

    for i in range(2, num//2):
        if num % i == 0:
            return False

    return True    # If we reached here, then no divisor was found.


# This incorrectly returns True
print(isprime(4))	      

This program reads data from a file of tweets. Each line starts with a date, followed by the tweet text, so you need to remove the date from the line. It's supposed to count how many tweets have "usna" or "naval academy" mentioned, but it's not working. Download the sample.tsv file and use a debugger to find out why not.

fh = open("sample.tsv")
count = 0

for line in fh:
  parts = line.split(',')
  text = parts[1]
  
  if 'usna' or 'naval academy' in text:
    count = count + 1

# Should print out 40!      
print('Found', count, 'mentions of USNA')