Skip to content

Notebook 14.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: Add two positive numbers

This function is supposed to accept two required arguments, add them together and return the sum. There are two at least two conditions that this function should handle which it currently doesn't: 1) If one of the passed in values is not strictly positive; and 2) If one of the values is not a number. Your goal is to get this function to work correctly. There are several ways to do this so we will discuss alternative strategies.

def add(a, b):
    if a > 0 and b > 0:
        return a + b

result = add(-1, 5)
print(result + 2)
Hints - Return values for functions that don't explicitly call `return` are set to `None`.
- You can use the function `type()` to get the type of a variable, and then test this in a conditional
- In the condition where a bad value is passed in (e.g. a string or char instead of an int) the decision of whether to return a 'safe' and sensible result or to raise an exception is up to you.

Challenge: Implement a 'Person' class

Here is a simple class that represents information about a "Person". This code block implements the Person class, instantiates a new person and tries to print it to the screen. Your goal is to fix this class to generate the expected output.

class Person:
    def __init__(self, name):
        '''Initialize the Person object'''
        self.name = name

    def __repr__(self):
        '''Describe the string representation of a Person'''
        return f"{self.name} is {self.age} years old"

p = Person("Phylo")
print(p)
The expected output is:
Phylo is 10 years old

Challenge: Implement a simple Dog class

This class describes a Dog with the ability to bark(). The expected output is Woof!. Your goal is to fix this class.

class Dog:
    def __init__(self, name):
        self.name = name
    def bark():
        print("Woof!")

d = Dog("Phylo")
d.bark()