Sub topic 2
Colons and indentation: how Python marks a block
This chapter assumes you can run a Python script or use the interactive interpreter. It also assumes you know the basic data types and can call print() and define a simple function. You do not need to know if yet. This chapter covers the layout rules that every if, elif, and else statement depends on.
Why layout matters in Python
Many languages group statements with braces ({ ... }) and treat whitespace as decoration. Python groups statements by position. A group of statements that run together is a block. Two pieces of syntax mark a block:
- A colon (
:) at the end of the line that introduces the block. - Indentation (leading spaces) on every line inside the block.
The line that ends in a colon is the header. The indented lines under it are the body. Python needs both, and it reports an error if either is missing.
The colon opens a block
A header line ends with a colon. In a conditional, the header contains a keyword (if, elif, or else), usually a condition, and then the colon.
temperature = 30
if temperature > 25:
print('warm')
print('wear light clothes')
print('done')The condition temperature > 25 is True, so Python runs the two indented lines. The line print('done') is not indented, so it is outside the block. It runs whatever the condition says.
The output is:
warm
wear light clothes
doneThe colon is part of the grammar. It is not optional, even when the body is obvious.
Indentation shows where the block ends
Python has no closing brace or end keyword. The block ends at the first line that is indented less than the body. This is called a dedent.
Compare the same two statements at different indentation levels:
temperature = 10
if temperature > 25:
print('warm')
print('this always runs')The condition is False, so the indented print('warm') is skipped. The last line is outside the block, so it runs and prints this always runs. If you indented that last line by mistake, it would be skipped as well. A wrong indent level in Python changes what the program does, not only how it looks.
The same rule applies to else and elif. These keywords must line up with the if they belong to, because Python matches them to an if by indentation.
temperature = 10
if temperature > 25:
print('warm')
else:
print('cool')
print('done')Here if and else start in the same column, and each has its own indented body. The dedent back to print('done') ends the else block.
How much to indent
Python does not fix the amount of indentation. It requires that every line in one block uses the same amount. The convention, from PEP 8 (the official style guide), is four spaces per level. Editors with Python support usually insert four spaces when you press Tab.
Follow these rules:
- Use four spaces per level.
- Do not mix tabs and spaces in the same file. Python 3 refuses to run code whose meaning depends on how wide a tab is.
- Configure your editor to insert spaces when you press Tab.
Blank lines and comment-only lines do not affect blocks. Python ignores them when it works out indentation, so you can add them freely for readability.
Nested blocks
A block can contain another block. Each level adds one more step of indentation, and each inner header again ends with a colon.
age = 20
has_ticket = True
if age >= 18:
print('adult')
if has_ticket:
print('entry allowed')
else:
print('buy a ticket')
print('end of check')The inner if and else sit four spaces deeper than the outer if. The line print('end of check') returns to column zero, which closes both blocks at once. Nested conditionals get their own chapter later. For now, notice that depth in the code matches depth in the logic.
A block needs at least one statement
A header followed by nothing is an error. Sometimes you want a branch that does nothing, or you want to add its code later. Use the pass statement, which does nothing.
def check(value):
if value < 0:
pass # TODO: decide how to handle negatives
else:
print('non-negative')
check(5)
check(-3)The call check(5) prints non-negative. The call check(-3) prints nothing, because the if branch runs pass. A comment alone would not be enough to fill the block, because Python ignores comments.
One-line bodies
If the body is a single simple statement, Python lets you put it on the header line.
count = 3
if count > 0: print('positive')This is valid. It is also discouraged by PEP 8, because it hides the block and makes later edits harder. If you add a second statement, you must move to the indented form. Prefer the indented form in every case except a short, deliberate one-liner.
Long conditions across several lines
Indentation rules apply to the start of a statement. Inside parentheses, Python lets a line continue onto the next line, and the extra indentation there is only for readability. The colon still goes at the end of the last line of the header.
width = 120
height = 80
depth = 40
if (width > 100
and height > 50
and depth > 20):
print('large box')The continuation lines are indented eight spaces so they stand apart from the body, which uses four. Without that extra indent, the condition lines would look like body lines.
Errors you will see
Python reports layout problems as SyntaxError or one of its subclasses: IndentationError, and TabError (a subclass of IndentationError). The script below compiles five broken snippets without running them, and prints the error type for each. It is a safe way to see the errors.
snippets = {
'missing colon': 'if True\n x = 1\n',
'no indent': 'if True:\nprint("x")\n',
'unexpected indent': 'x = 1\n y = 2\n',
'bad dedent': 'if True:\n x = 1\n y = 2\n',
'mixed tabs': 'if True:\n x = 1\n\ty = 2\n',
}
for name, source in snippets.items():
try:
compile(source, '<demo>', 'exec')
except SyntaxError as error:
print(name, '->', type(error).__name__)The output is:
missing colon -> SyntaxError
no indent -> IndentationError
unexpected indent -> IndentationError
bad dedent -> IndentationError
mixed tabs -> TabErrorThe table maps each error to its usual cause.
| Error | Typical cause | Fix |
|---|---|---|
| `SyntaxError` (expected `:`) | The header line has no colon. | Add the colon at the end of the header. |
| `IndentationError` (expected an indented block) | The line after the header is not indented. | Indent the body, or use `pass`. |
| `IndentationError` (unexpected indent) | A line is indented with no header above it. | Remove the extra indent. |
| `IndentationError` (unindent does not match) | A dedent lands on a level that no open block uses. | Align the line with an existing level. |
| `TabError` | Tabs and spaces are mixed in a way that is ambiguous. | Use spaces only. |
The exact wording of the messages differs between Python versions. Newer versions name the statement and line number, for example "expected an indented block after 'if' statement on line 1". The error type and the line number are the useful parts.
Summary of the rules
- A header line (
if,elif,else, and laterfor,while,def) ends with a colon. - The body is indented, and every line of one block uses the same indentation.
- The block ends at the first line with less indentation.
elifandelseline up with theifthey continue.- An empty body needs
pass. - Use four spaces, never a mix of tabs and spaces.
Read the code below and predict its output before you run it.
level = 2
if level > 1:
print('A')
if level > 5:
print('B')
print('C')Exercise
What does the code above print when level is 2, and what would change if print('C') were indented four spaces?
Show answer
It prints A and then C. The inner condition level > 5 is False, so B is skipped, and print('C') is at column zero, so it runs regardless. If print('C') were indented four spaces, it would belong to the outer if block. It would still run here because level > 1 is True, but it would be skipped for any level of 1 or less.
Exercise
This code raises an error: "if score >= 50" on one line, then "print('pass')" at the same indentation on the next line. Name the two separate problems and how to fix them.
Show answer
The header is missing its trailing colon, and the body is not indented. Write "if score >= 50:" and indent print('pass') by four spaces beneath it.