The basics of syntax

INPUT · Slides

The rules of indenting

01 / 06

A space at the start of a line is not decoration

In most languages you can put as many spaces as you like at the start of a line and nothing changes. They are there to look nice, and that is all.

Python is different. A space at the start of a line is part of the grammar. Put one where it does not belong and you get an error; leave one out where it is needed and you get an error too.

Those spaces are called the indent.

02 / 06

Putting one where it does not belong

Let us look at the error first. One single space at the start of the second line and Python stops dead.

IndentationError: unexpected indent means "there is an indent here that I was not expecting". It is saying "this is not a place to move right".

print("morning") print("noon")

Result

IndentationError: unexpected indent

03 / 06

Why give spaces a meaning at all

Most languages mark a group of lines (a block) by wrapping it in curly braces { }. Python dropped that and decided to show a block by how far it is indented.

The reasoning is simple: code that is easy to read is going to be indented anyway. So make the indent itself the rule, and you save the symbols and lose the arguments about style.

Put another way, indenting in Python is "write it so it can be read" turned into grammar.

04 / 06

A block is a colon plus an indent

The shape for starting a block is fixed. End the line with a : (a colon) and indent the lines after it.

The example below uses if, which is the next lesson — for now just look at the shape. See how the line after the : sits further right? Indented lines are the inside of the block.

score = 80if score > 60:    print("pass")

Result

pass

05 / 06

Indent by four spaces

Any amount of indent from one space upwards will run, but four spaces is the Python convention, so stick to it.

Within one block the width has to match, and that part is not optional. Four on one line and two on the next gives you IndentationError: unindent does not match any outer indentation level, which means "there is no block at that width".

score = 80if score > 60:    print("pass")  print("well done")

Result

IndentationError: unindent does not match any outer indentation level

06 / 06

Do not mix tabs and spaces

You can indent with tab characters, but mixing them with spaces gives you a TabError. They may look the same width, but they are different characters and Python can tell.

The editor here puts spaces in when you press tab, so you do not have to think about it. When you write on your own machine, decide on "spaces only" and stay there.

One tip for writing on a phone: when something will not work, suspect the start of the line first. An invisible space has crept in far more often than you would think.