Menu

Errors in algorithms

Syntax Errors

A syntax error is a mistake in the way the code is written: the code breaks the rules, or grammar, of the programming language. Every language has fixed rules about how statements must be formed, and any statement that does not follow them is a syntax error, however obvious its meaning is to a human reader.

Why the program cannot run

Before a program can run it must be translated into a form the computer can execute, by a compiler or an interpreter, and a translator cannot make sense of code that breaks the rules. A program containing a syntax error therefore cannot be translated, so it cannot run at all until the error is corrected. The translator checks the code before it runs and reports the first syntax error it finds, usually giving a line number, so these faults are discovered and fixed before any testing takes place.

Typical syntax errors

  • Missing or incorrect punctuation, such as a missing colon after an if condition.
  • A bracket or quotation mark that is opened and never closed.
  • A misspelled keyword, such as whille where while is needed.
  • Incorrect indentation where the language requires it, as Python does for the body of an if statement or a loop.
  • A keyword used in the wrong place, or multiplication written as x instead of *.
score = int(input())
if score >= 50
    print("Well done")

Output:

SyntaxError: expected ':' (line 2)

The if line has no colon at the end. You can tell what the programmer intended, but the statement does not follow the grammar of Python, so the translator reports the fault and nothing is run.

distance = 12
time = 3
speed = distance / (time * 60
print(speed)

Output:

SyntaxError: '(' was never closed (line 3)

Here the bracket opened before time * 60 is never closed, so the arithmetic cannot be worked out. Python reports this syntax error and stops translating, which means the program never reaches the point where it would run.

Practise this