← All lessons

Debugging: finding a bug

Sign in · Sign up

Lesson 13.2

When the code doesn't do what you expect, you look for the bug step by step:

  1. read the error — the last line of Python says what is wrong and where;
  2. print — output the value in the suspicious place: print(total);
  3. narrow it down — check the parts one by one: the input, the middle, the result;
  4. fix one thing and run it again — not ten things at once.

Here is code with a bug:

def average(numbers):
    total = 0
    for x in numbers:
        total += x
    return total / len(numbers) + 1   # an extra +1

print(average([2, 4, 6])) returns 6.0 instead of 4.0. print(total) shows 12 — the sum is right, so the extra bit is in the last line. For numbers only the sum matters, and + 1 is added to all of them.

The check gives the list of numbers numbers. Write average(numbers) and print Sum: <total> and Mean: <average> — that way you can see where the answer comes from.

Hint

The loop works out the sum, and the mean is the sum divided by the count.

The bug was the extra + 1 at the end. Print the sum first, then the mean — that way you can see where the mistake is if one appears again.