VP 12: Debugging in Google Colab (10 pts)

Background

One way to debug programs is to add extra print statements, and then comment them out when the code is fixed.

A debugger automates that process, and adds other useful features like breakpoints.

What You Need

A Google Colab environment. Open:
https://colab.research.google.com

Installing ipdb

We'll use the ipdb module to debug our code.

Execute these commands to install ipdb and configure it to automatically start when an error is detected:

!pip install ipdb
import ipdb
%pdb on
You see messages, ending with the line "Automatic pdb calling has been turned ON", as shown below.

Running Buggy Code

Execute this code:
# Code to Demonstrate PDB
num = 25
div = num%0 # The line which has error
 
print(div)
The output ends with an input field labelled ipdb>.

This field is waiting for debugging commands.

For now, just enter a q in the field and press Enter.

Adding a Breakpoint

Execute this code. Notice the line that sets the breakpoint.
def divide_num(n):
  for i in range(n,-1,-2):
    ipdb.set_trace()  # BREAKPOINT
    print(n%i)
 
x = divide_num(50)
print(x)
The output ends with an input field labelled ipdb>, as shown below.

Using p and c

Enter these commands into the ipdb> field to perform these actions:
p n,i   print the values of the variables n and i
c   continue execution
p n,i   print the values of the variables n and i
q   stop debugging
You can see how the variables change after the first cycle of the loop, as shown below.

VP 12.1: Simple Debugging (10 pts)

Execute this code:
a = 10
b = 23
c = 971
d = a * b * c
e = d % 99
f = e // 100
g = d / f
The program stops with an error.

Find the value of d at the point of the error.

That's the flag.

Python Ipdb Cheatsheet

For more ipdb commands, see:
Python Ipdb Cheatsheet

References

Debugging in Google Colab

Posted 9-15-24