3.2.11 - Finding and correcting program errors (Python)

3.2.11 - Finding and correcting program errors (Python)

Correct code must both obey Python's rules and implement the intended algorithm. You will distinguish syntax and logic errors, identify a fault from its behaviour and retest a focused correction.

Syntax errors

A syntax error breaks the programming language's rules for how statements are written.

Python
if score >= 10
    print("Pass")

The missing colon makes the statement invalid Python. An interpreter reports a syntax error rather than running the intended selection. Missing closing quotes or brackets and invalid indentation are further examples. A reported line is a useful starting point, but inspect the nearby preceding line too: an unclosed bracket or string may cause the parser to complain later.

The corrected form is:

Python
if score >= 10:
    print("Pass")

This can now be interpreted, assuming score exists, but syntactic correctness alone does not show that 10 is the appropriate pass mark. A program that runs may still implement the wrong requirement. Runtime failures such as division by zero are another possible problem; do not label every failed execution as a syntax error.

Logic errors

A logic error makes a syntactically valid program follow the wrong algorithm or rule.

Python
score = 10
if score > 10:
    print("Pass")
else:
    print("Retry")

If the requirement is a pass for at least 10, this program incorrectly refuses exactly 10. The syntax is legal; the comparison implements a different boundary. A normal score 12 would pass and could hide the error, so test the boundary 10. Wrong arithmetic, an accumulator reset inside a loop and an update outside the repeated body are other logic faults.

Trace actual state against intended state. For a sum of 1, 2, 3, starting total at 1 produces 7 instead of 6; the fault lies in the initial value, even though the later additions are correct. Find the first state that diverges rather than changing an arbitrary line near the final wrong output.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account