Debugging loops with print
In a loop the same lines run many times, with different values each time, so a bug can hide in any one of the iterations. Debugging prints are especially useful here: a print inside the loop shows what happens on every iteration.
This program should print the average of the numbers typed, but for 4 and 8 it prints 4.0 instead of 6.0:
total = 0
count = 0
while True:
number = int(input("Number (0 to finish): "))
count += 1
if number == 0:
break
total += number
print(f"Average: {total / count}")
4
8
0Number (0 to finish): 4
Number (0 to finish): 8
Number (0 to finish): 0
Average: 4.0Add a debugging print at the end of the loop's block, and another one right after the loop. Give each value a label, so you can tell them apart:
total = 0
count = 0
while True:
number = int(input("Number (0 to finish): "))
count += 1
if number == 0:
break
total += number
print("number:", number, "count:", count, "total:", total)
print("after the loop, count:", count, "total:", total)
print(f"Average: {total / count}")
4
8
0Number (0 to finish): 4
number: 4 count: 1 total: 4
Number (0 to finish): 8
number: 8 count: 2 total: 12
Number (0 to finish): 0
after the loop, count: 3 total: 12
Average: 4.0The values are right during the loop, but after it count is 3: the 0 that ends the input was counted too, because count += 1 comes before the check. Moving that line below the if fixes the program. Then the debugging prints can go.
What a break skips
A break ends the loop right where it stands, so on the last iteration the lines below it never run. Often that's just what you want: in the fixed program above, the 0 that ends the input must not be counted. But a check that comes too early makes the loop lose its last value. Suppose a loop should stop after the fifth score, but its if count == 5: with the break comes before the line that adds the score to the total. Then the fifth score is read and counted, but never added. A debugging print after the loop shows that the total is one value short, and following the last iteration line by line shows which line it never reached.
When you debug a loop, keep the number of iterations small at first: two or three are usually enough to see the problem, and the printed lines are still easy to read.