Syntax and indentation
Python has very little punctuation. Instead of braces and semicolons it relies on line breaks and indentation, which is why the code looks tidy but also why beginners hit IndentationError early on. This lesson covers the rules.
Statements end with a line break
One statement per line is the norm. No semicolon is needed.
x = 5
y = 10
print(x + y)You can put two statements on one line with a semicolon, but it is considered bad style and you will rarely see it.
Indentation defines blocks
In most languages a block of code is wrapped in { }. In Python a block starts after a line that ends in a colon : and consists of every following line that is indented by the same amount.
if 5 > 2:
print("Five is greater than two")
print("This line is also inside the if block")
print("This line is outside the block")The standard is four spaces per level. Most editors insert them automatically when you press Tab. Never mix tabs and spaces in the same file.
Getting the indentation wrong is a syntax error, not a style problem:
if 5 > 2:
print("This will fail")IndentationError: expected an indented block after 'if' statement on line 1All lines in one block must line up exactly:
if 5 > 2:
print("Four spaces")
print("Eight spaces: this is an error")Nested blocks
Blocks can contain blocks. Each level adds another four spaces.
for i in range(3):
if i % 2 == 0:
print(i, "is even")
else:
print(i, "is odd")Long lines
Inside brackets, parentheses or braces, Python lets a statement continue onto the next line without any special marker. This is the cleanest way to break long lines.
total = (1 + 2 + 3 +
4 + 5 + 6)
colours = [
"red",
"green",
"blue",
]
print(total, colours)Outside brackets you can use a backslash at the end of the line, but bracket continuation is preferred.
Case sensitivity
name, Name and NAME are three different variables. Keywords like if, for and True must be written exactly as shown.
Keywords
These words have special meaning and cannot be used as variable names:
False None True and as assert async await
break class continue def del elif else except
finally for from global if import in is
lambda nonlocal not or pass raise return try
while with yieldYou do not need to memorise them. Your editor will colour them differently, and Python will complain if you try to assign to one.
The pass statement
Sometimes you need a block that does nothing yet, for example a function you plan to write later. An empty block is a syntax error, so use pass as a placeholder.
def todo():
pass
todo()
print("pass does nothing, but the code runs")Practice
- Write an
ifstatement that checks whether a number is greater than 100 and prints a message in both cases. Pay attention to the colon and the indentation. - Deliberately indent one line by three spaces instead of four inside a block and read the error Python gives you.
