Writing error-free codeSyntax errors in practice

When writing programs, code should be as legible and error free as possible. Debugging helps keep code free of errors and documenting helps keep code clear enough to read.

Part ofComputer ScienceProgramming

Syntax errors in practice

The following code contains a in line 2:

name = input("What is your name? ")
pront("Hello, " + name)

The statement print is spelled incorrectly. The program will the first correctly then crash when it reaches the error.

The correct code is:

name = input("What is your name?")
print("Hello, " + name)

Syntax errors can be tricky to spot. Consider this short Python program:

forename = input("What is your forename? ")
surname = input("What is your surname? ”)
print "Hello, " + forname + " " + surname)

The code contains two errors, this time both in line 3:

  • The first is a punctuation syntax error. A bracket is missing after the print statement.
  • The second is a variable syntax error. The variable ‘forename’ is spelt incorrectly.

The program will execute the first two instructions correctly then crash when it reaches the first error in line 3.

The correct code is:

forename = input("What is your forename? ")
surname = input("What is your surname? ")
print("Hello, " + forename + " " + surname)

Fixing syntax errors is simple. Spotting them is more difficult. Some of the most common syntax errors are things that come in pairs. Always check for speech marks and brackets first if your program crashes.