Skip to content

Notebook 13.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: Find all elements smaller than a given number

This function is supposed to return a list of all values less than a given integer value. The function optionally takes a max_value, and it requires to pass in a list of numbers. Your goal is to get this function to work correctly. This code block has two errors, which you can solve consecutively.

def get_smaller(my_list, max_value='5'):
    """Return a list of all values smaller than max_value"""
    for element in my_list:
        low = []
        if element < max_value:
            low.append(element)
    return low

my_list = [5, 2, 12, 7, 3, 8]
get_smaller(my_list=my_list)

Challenge: Implement FizzBuzz

FizzBuzz is a classical programming challenge in which you are given the task to take consecutive integer values and print "Fizz" for each integer divisible by 3, "Buzz" for integers divisible by 5, and "FizzBuzz" for integers divisible by both 3 and 5, and remain silent for all other integers. In this case we have given you most of the code but there is an error, please fix it and verify that it works. This code block has two errors, which you can solve consecutively.

def fizzbuzz(max_num):
    "This method implements FizzBuzz"
    three_mul = 'fizz'
    five_mul = 'buzz'
    num1 = 3
    num2 = 5 

    # Google for 'range in python' to see what it does
    for i in range(1,max_num):
        # % or modulo division gives you the remainder 
        if i%num1==0 and i%num2==0:
            print(i,three_mul+five_mul)
        elif i%num1=0:
            print(i,three_mul)
        elif i%num2==0:
            print(i,five_mul)
fizzbuzz()

Challenge: Sum of positive integers

This function takes one argument, numbers, which should be a list of numbers. The function should sum all positive numbers in this list. Why doesn't it work?

def sum_positive(numbers):
    total = 0
    for num in numbers:
        if num > 0:
            total + num
    return total

sum_positive([1,2,3,4,5,6,7])