Beginner   Chapter 11 · 20 min read · Module 1: Python Fundamentals

Python Indentation

Learning objectives
  • 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.

Block: a group of statements that belong together and run as one unit, for example the body of an if statement or a function

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.

Example 1: A simple if block
age = 20
if age >= 18:
    print("You can vote")
    print("Please carry your ID")
print("Done")
You can vote Please carry your ID 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.

StyleSpaces per levelComment
PEP 8 style4Recommended and most common
Two-space style2Allowed, but unusual in Python
Tabs only1 tabAllowed, but spaces are preferred
Mixed tabs and spacesvariesCauses 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.

Example 2: Nested loop and if
for number in range(1, 5):
    if number % 2 == 0:
        print(number, "is even")
    else:
        print(number, "is odd")
    print("checked", number)
print("finished")
1 is odd checked 1 2 is even checked 2 3 is odd checked 3 4 is even checked 4 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.

Example 3: Indentation in a function
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))
A B C

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.

Example 4: What the error looks like
if True:
print("hello")
File "example.py", line 2 print("hello") ^ IndentationError: expected an indented block after 'if' statement on line 1
Python 3.10 and newer give clearer messages such as "expected an indented block after 'if' statement". Older versions only said "expected an indented block".

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.

Example 5: Using pass as a placeholder
def todo():
    pass

for i in range(3):
    pass

print(todo())
print("ok")
None 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.

Example 6: A list over several lines
fruits = [
    "apple",
    "banana",
    "cherry",
]
print(len(fruits))
print(fruits[-1])
3 cherry

Python syntax

Syntax
if condition:
    statement_1
    statement_2
Syntax
for item in sequence:
    if test:
        statement
    else:
        statement
Syntax
def name(parameters):
    statement
    return value

Real-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

Mistake: Forgetting to indent the line after a colon
Fix: Indent the body by four spaces, or write pass if the block should be empty for now.
Mistake: Mixing tabs and spaces in one file
Fix: Set your editor to insert spaces when you press Tab and convert old tabs to spaces.
Mistake: Using a different number of spaces for lines of the same block
Fix: Keep one consistent amount, normally four spaces, for every line in the block.
Mistake: Indenting a line that is not part of any block
Fix: Remove the extra spaces so the line starts at the left edge or matches the line above.
Mistake: Writing a comment where a statement is required
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

Related chapters