Python Syntax
Syntax is the set of rules that says how code must be written, just as grammar says how sentences are written. Python's rules are few, and most of them exist to make code easy to read. The most important one, and the one that surprises people who know other languages, is that indentation matters.
One statement per line
A statement is one instruction: print something, give a variable a value, call a function. In Python you normally write one statement on each line, and the end of the line ends the statement. No semicolon is needed:
Indentation makes blocks
Some statements, such as if, for, while and def, control a group of other statements, called a block. The controlling line ends with a colon, and the lines of the block are indented: they start further to the right, usually by 4 spaces. The block ends where the indentation goes back:
temperature = 31
if temperature > 30:
print("It is hot today.")
print("Drink some water.")
print("This line always runs.")It is hot today. Drink some water. This line always runs.
The two indented lines belong to the if; the last line does not. Other languages use curly brackets for blocks and indentation only for looks. In Python the indentation is the structure, so it must be consistent: every line of a block starts at the same column. If it does not, Python stops with an IndentationError. Use spaces, not tabs, and four spaces per level; the editor indents for you when you press Enter after a colon.
Case sensitivity
Python is case-sensitive: name, Name and NAME are three different names. The same goes for keywords and functions: print works, but Print is unknown and gives a NameError. Keywords such as if, for, True and None must be written exactly as they are.
Long lines
A statement can continue on the next line while a bracket is still open. This is the usual way to break a long line:
Practice exercises
- Write an
ifblock with three indented lines, then a line that is not indented. Run it with a value that makes the condition true, then false. - Indent one line of the block by 2 spaces instead of 4 and read the error.
- Write
Print("hi")with a capital P and read the error and the hint. - Split a long sum over three lines using brackets.