Syntax Error vs Logic Error: What's the Difference?
Learn the difference between syntax errors and logic errors in GCSE Computer Science, with simple Python examples and tips for spotting each when testing code.
A syntax error breaks the rules for writing code, so the program cannot run as written. A logic error means the code can run, but it does not do what the programmer intended.
Syntax errors
Syntax is the set of rules a programming language uses to decide whether code is written correctly. In Python, this line is missing a closing bracket:
print("Ready"
Python reports an error because it cannot interpret the incomplete instruction. Adding the closing bracket fixes the syntax:
print("Ready")
An error message often helps you find a syntax error. Check the line it points to, but also look at the line just before it: that may be where a bracket or quotation mark was left open.
Logic errors
A logic error is a mistake in the steps or conditions used to solve a problem. Suppose a program should print Eligible for anyone aged 181818 or over:
if age > 18:
print("Eligible")
This code has valid syntax and runs. However, it excludes someone who is exactly 181818, so the result is wrong for that input. The condition should include 181818:
if age >= 18:
print("Eligible")
To find a logic error, test the program with inputs where you know the expected result. For this example, checking ages just below, exactly at and just above 181818 helps reveal the mistake.
A trace is a step-by-step check of what a program does for a chosen input. For age=18age=18age=18, the original condition age>18age>18age>18 is false, so nothing is printed. The corrected condition age≥18age\geq18age≥18 is true, so it prints Eligible. Comparing the actual result with the expected result makes the faulty condition easier to identify.
Exam mistake to avoid: Do not call every incorrect result a syntax error. If the program runs but produces the wrong result, look for a logic error.