6.1.5 Identifying and correcting errors

Three Types of Error in Programs

The three types of programming error are syntax, runtime and logic. Each requires a different approach to locate and correct. This benchmark focuses on identifying and fixing them in actual code.

Error typeWhen detectedProgram runs?How to find it
SyntaxBefore execution (compile/parse time)NoError message shows line number and type
RuntimeDuring executionCrashes partwayException message; trace to the line that executes
LogicDuring testingYes, but wrong outputTrace tables; test data; print statements; debugger

Worked Examples

# Python — Syntax errors prevent execution
score = int(input("Enter score: ")
if score >= 50              # Missing colon
    print("Pass")
else:
    print("Fail")

Errors: (1) missing closing parenthesis ) on line 1; (2) missing colon : after the if condition on line 2. Python raises a SyntaxError and shows the approximate line. The program will not start until both are fixed.

# Fixed
score = int(input("Enter score: "))
if score >= 50:
    print("Pass")
else:
    print("Fail")
# Python — Runtime errors occur during execution
numbers = [10, 20, 30]
index = int(input("Enter index: "))
print(numbers[index])         # IndexError if index >= 3 or < -3

total = int(input("Total: "))
people = int(input("People: "))
share = total / people        # ZeroDivisionError if people == 0

Issues: no bounds check before accessing numbers[index]; no guard against dividing by zero.

# Fixed — add guards before the risky operations
numbers = [10, 20, 30]
index = int(input("Enter index (0-2): "))
if index >= 0 and index < len(numbers):
    print(numbers[index])
else:
    print("Index out of range")

total = int(input("Total: "))
people = int(input("People: "))
if people == 0:
    print("Cannot divide by zero")
else:
    share = total / people
    print("Share:", share)
# Python — Logic error: runs but gives wrong output
# Intended: calculate the average of a list
scores = [70, 85, 60, 90]
total = 0
for score in scores:
    total = total + score
average = total / 5          # BUG: divides by 5 but list has 4 items
print("Average:", average)   # Prints 61.25 instead of 76.25

Issue: hardcoded divisor 5 does not match the list length 4. No error message — the wrong answer is silently produced.

# Fixed — use len() to get the actual list length
scores = [70, 85, 60, 90]
total = 0
for score in scores:
    total = total + score
average = total / len(scores)   # Always correct regardless of list size
print("Average:", average)      # Output: 76.25

 Key Takeaways

  • Syntax: breaks language rules — program will not run; error message gives line number.
  • Runtime: crashes during execution — add guards before risky operations (index access, division).
  • Logic: runs but gives wrong output — use trace tables, test with known inputs, use len() not hardcoded sizes.
  • Never hardcode the length of a list — use len() so the code works correctly if the list changes size.