Skip main navigation

New offer! Get 30% off your first 2 months of Unlimited Monthly. Start your subscription for just £29.99 £19.99. New subscribers only. T&Cs apply

Find out more

Syntax

Why is syntax so important for programming? In this article, Martin O'Hanlon explains how to make sure that the computer understands you.

Now you are starting to create more complex instructions, it’s time to talk about syntax, the inevitable “syntax errors”, and tips for resolving them.

Syntax is a set of rules which describe how the code must be laid out. Computers are sticklers for precision, and if you break the rules they will tell you in the only way they know how: with errors. They just don’t have the imagination to cope with anything unusual!

Let’s talk through some of the syntax rules for this line of code:

users_name = input("What is your name? ")

users_name – this is the variable name and there are syntax rules about how variables can be named, one being that variable names cannot contain a space.

If you were to run the following code, you would be presented with an error (also below):

users name = input("What is your name? ")
^
SyntaxError: invalid syntax

The Mu IDE, with 'users name = input("What is your name? ")' in the editor. The REPL repeats this line with an arrow pointing at the end of "users name". Below this the REPL reads "SyntaxError: invalid syntax

Python is telling you that you have broken the rules and you need to fix the problem otherwise your program cannot be run.

In this snippet of code, the function input is being used. We must give it a prompt for the user, and the syntax rules say we must enclose this prompt in round brackets (). Missing out either or both of the brackets will result in an error.

users_name = input "What is your name? "
^
SyntaxError: invalid syntax

The Mu IDE, with 'users_name = input "What is your name? "' in the editor. The REPL repeats this line with an arrow pointing at the end of the line. Below this the REPL reads "SyntaxError: invalid syntax

There are many rules which govern syntax and a deep understanding comes with practice and experience, but the basics are easy to understand and will be introduced throughout this course.

Tip: when presented with a SyntaxError, use the error message to find the approximate position of the error. It could be the line before or after the one shown. Be critical of your own code or get someone else to look over it for you.

This article is from the free online

Programming 101: An Introduction to Python for Educators

Created by
FutureLearn - Learning For Life

Reach your personal and professional goals

Unlock access to hundreds of expert online courses and degrees from top universities and educators to gain accredited qualifications and professional CV-building certificates.

Join over 18 million learners to launch, switch or build upon your career, all at your own pace, across a wide range of topic areas.

Start Learning now