Informatics Practices · Ch 3 — Brief Overview of Python
Logical Errors
Logical Errors
A logical error — also called a bug, or a semantic error — is the sneakiest of the three error types, because it does not stop the program at all. The program executes from start to finish, apparently successfully, yet behaves incorrectly and produces undesired or wrong output. The flaw is not in how the code is written but in what the code says to do.
This is precisely what makes logical errors difficult to identify: since the program interprets and runs successfully even while the error is present, there is no error message, no crash, nothing to point a finger at the mistake. The only symptom is output that does not match what you expected — and you notice that only if you know what the correct output should be.
Consider a concrete case. Suppose we wish to find the average of the two numbers 10 and 12, and we write the code as:
10 + 12/2
This runs successfully and produces the result 16 — which is wrong. Division has higher precedence than addition, so Python computes 12 divided by 2 first (giving 6) and then adds 10. The code we should have written is:
(10 + 12)/2
which correctly produces the output 11. The parentheses ensure the two numbers are added before the sum is halved — matching what "average" actually means. …