Lesson 13.2
When the code doesn't do what you expect, you look for the bug step by step:
print — output the value in the suspicious place: print(total);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.
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.