Sub topic 2
Colons and Indentation: How Python Marks a Block
What this chapter assumes
You can run a Python script, you know the basic types (int, str, bool, list, dict, None), and you can call print(). This chapter covers the layout rules that every if, elif, and else depends on.
What a block is
A block is a group of statements that run together under one controlling line. Many languages wrap a block in braces. Python uses a colon at the end of the header line, plus indentation (spaces at the start of a line) for the lines inside.
temperature = 31
if temperature > 30:
print('hot')
print('drink water')
print('done')With temperature = 31, this prints hot, drink water, and done. With temperature = 20, it prints only done. The last print is indented less, so it is outside the block and always runs.
The two rules
- The header line (
if ...,elif ...,else) must end with a colon. - The lines in the block must be indented, all by the same amount. The block ends at the first line indented less.
Choosing an indent size
Use four spaces per level, which is the standard style in PEP 8. Set your editor so the Tab key inserts four spaces. Do not mix tabs and spaces in one file. Python 3 refuses to guess how they line up and raises a TabError.
Keeping else aligned
elif and else belong to the if above them. They must start at the same indentation as that if, and each gets its own indented block.
age = 16
if age >= 18:
print('adult')
print('can vote')
else:
print('minor')
print('cannot vote yet')Python runs exactly one of the two blocks. Here it prints minor and cannot vote yet.
Common errors
| Message | Cause | Fix |
|---|---|---|
| `SyntaxError: expected ':'` | The header line has no colon. | Add `:` at the end of the line. |
| `IndentationError: expected an indented block after 'if' statement` | The line after the header is not indented, or there is no body. | Indent the body. |
| `IndentationError: unexpected indent` | A line is indented but no header opened a block. | Remove the extra spaces. |
| `IndentationError: unindent does not match any outer indentation level` | A line dedents to a column that matches no earlier level. | Align it with an existing level. |
| `TabError` | Tabs and spaces are mixed ambiguously. | Use spaces only. |
Python's indentation rules are enforced, but they cannot catch a wrong choice about where a block ends. If you indent a line that should run every time, the program runs without an error and gives the wrong result.
An intentionally empty block
A block needs at least one statement. When you want a branch that does nothing yet, use pass.
x = 5
if x > 3:
pass
else:
print('small')This prints nothing, because the if branch runs and does nothing.
Exercise
This code raises an error. Name the error type and the fix. if score >= 50 print('pass')
Show answer
It is a SyntaxError (expected ':'). The header line if score >= 50 is missing its colon, so the fix is if score >= 50:. The print line is already indented correctly.