📊 Investigate: Find the Logic Error
Logic errors are tricky because the code runs without crashing - but gives wrong results. Trace through the code carefully to find where it goes wrong!
Remember: Logic errors don't show error messages. You find them by tracing the code step by step and checking if the output matches what you expect.
Debugging Strategies for Logic Errors
1. Print Debugging
Add print statements to see what values variables have at different points:
total = 0
for num in [1, 2, 3]:
total + num
print(f"After adding {num}, total = {total}") # Debug line
print(total)
Output reveals: "total = 0" every time - the bug is clear!
2. Check Your Assumptions
Write down what you EXPECT to happen, then trace what ACTUALLY happens:
# I expect: range(1, 5) gives 1, 2, 3, 4, 5
# Actually: range(1, 5) gives 1, 2, 3, 4
# The bug: range stops BEFORE the end value!
3. Trace Tables
Track every variable's value at each step of the program:
| Step | i | total | Notes |
|---|---|---|---|
| Start | - | 0 | Initialised |
| Loop 1 | 1 | 0 | total + 1 calculated but not stored! |
| Loop 2 | 2 | 0 | Same problem |
4. Rubber Duck Debugging
Explain your code line by line to someone (or something!) else. Often you'll spot the bug while explaining:
"So here I'm adding num to total... wait, I'm not STORING it anywhere!"