Menu

Syntax and Logical Errors

Correcting Program Errors

Correcting a program error follows three steps: identify the type of error, locate the faulty line, then amend that line so the code follows the rules of the language and produces the result you intended. Naming the type first tells you what kind of change to make, so you are fixing rather than guessing.

  • Identify: a program that will not start, one that crashes part-way through, and one that finishes with the wrong answer point to different kinds of fix.
  • Locate: find the line responsible before you change anything.
  • Amend: change as little as possible. Rewriting lines that already work can add fresh errors.

Syntax and runtime errors

For a syntax error, correct the punctuation, such as a missing colon or an unclosed bracket, or a name that breaks the rules, such as one starting with a digit.

When a runtime error is caused by an operation that is impossible for some inputs, do not simply remove the offending line. Add a check before it so the impossible operation is never attempted, and make the alternative path do something useful with the data. The change has to make sense for the program's logic, not just stop the crash.

# check the position before it is used
scores = [12, 7, 20, 5]
position = int(input("Which position? "))
if position < 1 or position > len(scores):
    print("That position does not exist")
else:
    print(scores[position - 1])

Output when the user types 7:

Which position? 7
That position does not exist

Without the check, entering 7 would ask for an item that does not exist and the program would stop with an error. The check catches the bad value first and gives the user a sensible message instead of a crash.

Logic errors

A logic error is corrected by changing the design of the code rather than its grammar: alter the condition, the operator, the variable being updated, or the indentation that decides which statements sit inside a selection or a loop. Your target is that the output matches the intended design.

age = int(input("How old are you? "))
if age > 13:
    print("Welcome to the club")
else:
    print("Sorry, you must be 13 or over")

Output when the user types 13:

How old are you? 13
Sorry, you must be 13 or over

Someone who is exactly 13 is old enough to join, so the condition should be age >= 13. Changing that one operator leaves the rest of the program untouched and makes the message match the rule.

Practise this