1.12

# Syntax

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


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


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.