Skip to content

Notebook 15.0 Debugging Challenges

This notebook will give some practice in debugging python code, and reading, understanding, and responding to python error messages in small functions.

Learning objectives

  • Understanding python error messages
  • Debugging python scripts

Methodology

This tutorial involves identifying and fixing small errors or bugs in python code. For this set of challenges you will open a new jupyter notebook, copy the code from each of the challenges, and attempt to fix each of them according to the directions. You may use whatever to do this that are at your disposal.

Hint: Remember that using print() statements inside functions is a good way to easily trace execution.

Challenge: Load a dataset from a csv

The following code will download a small dataset that we will use in the machine learning exercise today. There is a bug in this code that you'll need to find and fix in order to proceed with the exercise later.

import requests
url = "https://raw.githubusercontent.com/eaton-lab/hack-the-planet/refs/heads/master/docs/data/penguin_data.csv"

with open("penguin_data.csv", 'w') as outfile:
    outfile.write(requests.get(url).text)

data = penguin_data.csv
df = pd.read_csv(data)

Challenge: Testing multiple conditions in an if statement

Here is a quick function to test whether either of the two first input values are less than the third (optional) value that defaults to 4.

def either_less(a, b, c=4):
    if a or b < c:
        print("Both are less")
    else:
        print("Both aren't less")

either_less(3, 5)
The expected output (only if both input values actually are less):
Both are less

Challenge: Fix all the bugs in one shot

Here is a different kind of challenge. This code should just print a message to the console but there are many small problems with it. See how many of the bugs you can fix before running this cell to test it. Keep track of how many bugs you find before you get this code to run. How many was it total?

if true
print helloworld