This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 10: Debugging and testing

Debugging exercise

face Josiah Wang

Now, let’s get you to practice more debugging.

Below is a program that does not produce the expected output. Make it work correctly!

Hint: You need to add two things to the code.

You might notice a few things in the code that we have not yet covered - this is a sneak preview for the next lesson! See if you can understand what the code is doing just by reading it! It is also possible to write this code only with what we have covered so far (you can try this in your spare time).

Sample expected output:

user@MACHINE:~$ python prime_sum.py
Please enter an integer: 1
2
user@MACHINE:~$ python prime_sum.py
Please enter an integer: 2
5
user@MACHINE:~$ python prime_sum.py
Please enter an integer: 3
10
user@MACHINE:~$ python prime_sum.py
Please enter an integer: 4
17
user@MACHINE:~$ python prime_sum.py
Please enter an integer: 5
28
user@MACHINE:~$ python prime_sum.py
Please enter an integer: 6
41

The code to fix:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def read_integer():
    return int(input("Please enter an integer: "))


def is_divisible_by(number, divisor):
    return number % divisor == 0


def is_prime_number(number):
    if number <= 1:
        return False

    divisor = 2
    while divisor < number:
        if is_divisible_by(number, divisor):
            return False
        else:
            divisor += 1
    return True


def get_prime_number_list(n):
    prime_number_list = []

    current_number = 2
    while len(prime_number_list) < n:
        if is_prime_number(current_number):
            prime_number_list.append(current_number)

    return prime_number_list


def sum_prime_number_list(prime_number_list):
    total = 0
    for number in prime_number_list:
        total += number


def sum_first_n_prime_numbers(n):
    prime_number_list = get_prime_number_list(n)
    total = sum_prime_number_list(prime_number_list)
    return total


n = read_integer()
total = sum_first_n_prime_numbers(n)
print(total)

No peeking at the solutions before fixing it yourself! 👀

Solution to the above problem:

  1. Add return total to Line 37 (with a 4-space indentation)
  2. Add current_number += 1 to Line 29 (with an 8-space indentation)