indusai.co

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.

python
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.

python
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:

python
if 5 > 2:
print("This will fail")
output
IndentationError: expected an indented block after 'if' statement on line 1

All lines in one block must line up exactly:

python
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.

python
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.

python
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:

output
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     yield

You 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.

python
def todo():
    pass

todo()
print("pass does nothing, but the code runs")

Practice

  1. Write an if statement that checks whether a number is greater than 100 and prints a message in both cases. Pay attention to the colon and the indentation.
  2. Deliberately indent one line by three spaces instead of four inside a block and read the error Python gives you.