Menu

Writing and Refining Algorithms

Common Syntax Errors

A syntax error is a mistake that breaks the rules of Python, so the program cannot run. You need to find and correct punctuation, spelling and indentation mistakes in code.

Punctuation and layout

Every if, elif, else, for and while line must end with a colon. The colon tells Python that an indented block follows. Lines inside that block must be indented, and every line in the same block must line up. If one line is indented differently, Python cannot tell which block it belongs to.

Every opening bracket needs a closing bracket, and text must have quotation marks at both ends. To join two strings into one, put + between them; without it Python cannot build the combined string. Multiplication uses *, not x: 9 x 4 is invalid because Python does not treat x as a multiplication sign.

score = 8
if score > 5
    print("Well done")

Output:

SyntaxError: expected ':' (line 2)

Keywords and names

The keywords used in these constructs are lower case and must be spelt exactly. Write elif as one word, not else if; it is followed by a condition, while else is used when there is no condition to test. A keyword typed with the wrong letters, such as fro instead of for, is not recognised.

Python is case sensitive: total, Total and TOTAL are three different names. If you store a value in total but later print Total, Python stops when it reaches that line because Total has no value.

Practise this

OCR GCSE Computer Science · Writing and Refining Algorithms