Computer Science · Ch 5 — Getting Started with Python
Logical Errors
Logical Errors
A logical error is a bug in the program that causes it to behave incorrectly — the program runs, but does the wrong thing. A logical error produces an undesired output, yet without any abrupt termination of the program's execution.
Why logical errors are hard to find
Because the program interprets (runs) successfully even when logical errors are present, these errors can be difficult to identify. There is no error message, no crash — nothing flags the problem. The only evidence of a logical error is the wrong output. The standard technique is to work backwards from the output: given that the result is wrong, trace the calculation in reverse to identify what went wrong.
Example: a wrong average
Suppose we want the average of the two numbers 10 and 12, and we write:
>>> 10 + 12/2
16.0
The code runs successfully and produces 16 — but 16 is certainly not the average of 10 and 12. The bug is one of operator precedence: division binds tighter than addition, so Python computed 10 + (12/2) = 10 + 6 = 16. The correct code parenthesises the sum first:
>>> (10 + 12)/2
11.0
Now the output is the correct average, 11.