Beginner Chapter 11 · 20 min read · Module 1: Python Fundamentals
Python Indentation
- After this chapter you can explain why indentation is part of Python's syntax.
- You can write correct blocks for if, for, while and def statements.
- You can use nested blocks with the right number of spaces.
- You can fix IndentationError, TabError and unexpected-indent mistakes.
- You can follow the common style rule of four spaces per level.
Many languages use curly brackets to show which lines belong together. Python does it in a simpler way: it uses the empty space at the start of a line. This space is called indentation, and in Python it is not just decoration. It tells the interpreter which statements are inside an if, a loop or a function.
Because of this rule, Python code always looks tidy. You cannot write a program with messy layout and still have it run. This is one reason why Python is easy to read, but it also means that a single extra space in the wrong place can stop your program with an error.
In this chapter you will learn what a block is, how to indent it, how nested blocks work, and which errors appear when indentation is wrong. You will also learn the style rules that most Python programmers follow.
What is indentation?
Indentation means the spaces at the beginning of a line, before the first visible character. In many languages these spaces are only for humans. In Python they are part of the grammar. Lines that have the same indentation and sit next to each other form a block.
A block always starts after a line that ends with a colon :. Statements such as if, elif, else, for, while, def, class, try and with all end their first line with a colon. The next line must then be indented more than that first line. When you go back to the earlier indentation, the block ends.
age = 20
if age >= 18:
print("You can vote")
print("Please carry your ID")
print("Done")The two print lines under the if are indented, so they only run when the condition is true. The last print has no indentation. It is outside the block and runs every time. Try changing age to 15 and you will see that only Done appears.
How many spaces should you use?
Python does not force a fixed number of spaces. The rule is that all lines in one block must use the same amount. The official style guide, called PEP 8, recommends four spaces for each level. Almost every editor can insert four spaces when you press the Tab key, so you do not need to count by hand.
Avoid mixing tabs and spaces in the same file. A tab can look like four spaces on your screen and eight on another, so the code may look right but behave wrongly. Python 3 refuses to guess and raises a TabError when the mix is confusing. The simplest habit is to configure your editor to use spaces only.
| Style | Spaces per level | Comment |
|---|---|---|
| PEP 8 style | 4 | Recommended and most common |
| Two-space style | 2 | Allowed, but unusual in Python |
| Tabs only | 1 tab | Allowed, but spaces are preferred |
| Mixed tabs and spaces | varies | Causes TabError, avoid it |
Nested blocks
A block can contain another block. This is called nesting. Each new level is indented further, usually by four more spaces. The deeper a line is, the more conditions or loops it depends on. Reading the indentation from left to right tells you the structure of the program.
for number in range(1, 5):
if number % 2 == 0:
print(number, "is even")
else:
print(number, "is odd")
print("checked", number)
print("finished")The outer for body has three parts: the if and else blocks, and the print that follows them. That last print lines up with the word if, so it runs on every loop turn. The final print has no indentation, so it runs once after the loop ends.
Indentation in functions
A function body is also a block. Everything inside the function must be indented below the def line. When you return to the left edge, the function definition is over. Python reads the whole function first and only runs the body when you call it.
def describe(score):
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
else:
grade = "C"
return grade
print(describe(95))
print(describe(80))
print(describe(40))Common indentation errors
There are three errors you will see often. An IndentationError: expected an indented block appears when a line ends with a colon but the next line is not indented. An IndentationError: unexpected indent appears when a line is indented without any reason, for example after a normal statement. An IndentationError: unindent does not match any outer indentation level appears when you go back to a level that was never used before.
if True:
print("hello")Empty blocks and the pass statement
Sometimes you want to write the structure first and fill in the details later. A block cannot be empty, because Python would raise an error. The pass statement does nothing, and it is the correct way to fill an empty block. Comments alone are not enough, because they are ignored by the interpreter.
def todo():
pass
for i in range(3):
pass
print(todo())
print("ok")Continuation lines and brackets
Inside brackets, indentation of the continued lines does not matter to Python. You can split a long list or a long function call over several lines and indent them in any way that looks readable. This is called implicit line joining. Blank lines and comment-only lines are also ignored when Python checks indentation, so you can use them to separate parts of your code.
fruits = [
"apple",
"banana",
"cherry",
]
print(len(fruits))
print(fruits[-1])Python syntax
if condition:
statement_1
statement_2for item in sequence:
if test:
statement
else:
statementdef name(parameters):
statement
return valueReal-world applications
- Writing readable functions and classes that other people can maintain.
- Structuring conditions and loops in every Python program.
- Reviewing code quickly, because the layout shows the logic.
- Working in teams that use style tools such as linters and formatters to keep indentation consistent.
Common mistakes
Fix: Indent the body by four spaces, or write pass if the block should be empty for now.
Fix: Set your editor to insert spaces when you press Tab and convert old tabs to spaces.
Fix: Keep one consistent amount, normally four spaces, for every line in the block.
Fix: Remove the extra spaces so the line starts at the left edge or matches the line above.
Fix: Use pass, because a block with only comments is still empty.
Important tips
- Turn on visible whitespace in your editor to spot tabs and spaces.
- Let the editor indent automatically after you type a colon and press Enter.
- Avoid more than three or four levels of nesting; move code into functions instead.
- Use a formatter such as black to fix layout for you.
Key points summary
- Python uses indentation, not brackets, to define blocks.
- A block starts after a line ending with a colon.
- Use the same indentation for all lines in a block; four spaces is the standard.
- Do not mix tabs and spaces.
- The pass statement fills a block that must exist but does nothing.
Exam and interview points
- Indentation defines the scope of a block in Python; it is mandatory syntax.
- A missing indent after a colon raises IndentationError.
- Mixing tabs and spaces can raise TabError in Python 3.
- PEP 8 recommends four spaces per indentation level.
- pass is a null statement used as a placeholder.
Quick revision
- Colon at the end of a line means: indent the next line.
- Same block means same indentation.
- Four spaces per level.
- Never mix tabs and spaces.
- Use pass for an empty block.
Frequently asked questions
Can I use tabs instead of spaces?
Yes, as long as you use only tabs in the whole file. But the Python style guide prefers four spaces, and most projects follow it.
Why does Python use indentation instead of braces?
The designers wanted code to be easy to read. Forcing the layout to match the structure means all programs look clear and the structure cannot hide behind a different layout.
What happens if I use two spaces in one line and four in the next line of the same block?
Python raises an IndentationError (unexpected indent or unindent does not match), because lines in the same block must have the same indentation.
Does indentation matter inside brackets?
No. Inside (), [] and {} the continuation lines can be indented freely. The rule applies only to the start of a normal statement.
Do blank lines affect indentation?
No. Blank lines and lines containing only a comment are ignored when Python checks the indentation.
Practise this chapter
21 practice questions Take the chapter quiz