Sitelet https://www.askpython.com/python/python-indentation

What Is Indentation in Python?

Python uses indentation — not braces — to define code blocks. Learn Python indentation rules, common IndentationError examples, and best practices to write clean, bug-free code.

Writing a Python function or conditional means deciding which statements belong inside its body. Indentation marks those statements as a group in Python.

I’ll walk through a function and conditional, then explain how to correct common indentation errors.

TL;DR

Python indentation is the leading whitespace that marks which statements belong to a code block, and four spaces per level is the PEP 8 convention.

  • Indent the body after a compound statement’s colon.
  • Keep statements in one block at the same indentation level.
  • Use spaces consistently and do not mix tabs and spaces.

What Is Indentation in Python?

Indentation is the leading spaces or tabs that mark a suite, the group of statements controlled by a function, loop, conditional or class.

A colon ends a compound statement’s header, and the tokenizer represents level changes with INDENT and DEDENT tokens.

In an if statement, Python evaluates the condition when execution reaches the branch.

Loop and class definitions use the same colon-and-suite form, so this syntax appears throughout ordinary Python programs.

The word suite is the term used for this grouped set of statements.

How to Indent a Python Block Step by Step

The example pairs a function and conditional with a loop at module level. I chose it to show nested and sibling suites in one run.

Step 1: Write the block header

Write a Boolean condition after if, then end the header with a colon.

def classify(score):
    if score >= 60:
        return "pass"
    return "retry"


for score in (72, 45):
    print(f"{score}: {classify(score)}")

Step 2: Indent the suite body

The function returns pass for scores of 60 or more and retry otherwise. The loop calls it once for each score in the tuple.

I ran the file with python3 indentation_demo.py. The terminal showed:

72: pass
45: retry
Python if block indentation shown in terminal output
Running the indented function prints a different result for each score.

The output shows the condition selecting the first return for 72, while 45 reaches the function’s next return.

Step 3: Use a consistent indentation style

PEP 8 recommends four spaces per indentation level and prefers spaces. I use four spaces in the example so each level is visible.

When an if has an else clause, align else with if rather than with either branch body.

Python Indentation Errors and Edge Cases

Tracebacks name an indentation exception and the source line where Python detected a problem. The table maps common messages to a correction.

CaseTypical messageWhat to check
Extra indent without an open suiteunexpected indentRemove leading whitespace or add the intended enclosing statement.
Missing body after a colonexpected an indented blockIndent the suite or use pass as a temporary body.
Dedent to a level Python never sawunindent does not match any outer indentation levelAlign with a previous block level.
Tabs and spaces make the level ambiguousTabErrorReplace leading whitespace with spaces consistently.

Put pass on an indented line when a suite is intentionally unfinished. An indented first executable line is valid inside a function or other enclosing block.

Python expands tabs when it calculates indentation, and an ambiguous combination raises TabError. Replace the block’s leading whitespace with spaces consistently.

Continuation lines inside parentheses, brackets or braces have separate formatting rules from suites. Their alignment can aid readability without marking a new compound statement body.

The reported line can appear after the whitespace mistake that caused the failure. Inspect the preceding header and its body, especially after copying code between editors that display tabs at different widths.

A blank line within a function or conditional separates nearby statements for readers, but the suite continues until a later statement changes its level. A comment-only line also leaves the surrounding structure intact.

Conclusion: Indentation Defines the Block

For the formal lexical rules, read the Python language reference on indentation. Related examples appear in AskPython guides to Python if, elif and else and Python for loops.

FAQ

These short answers cover common indentation questions that do not need another full section.

How many spaces should I use for indentation in Python?

PEP 8 recommends four spaces for each indentation level. Use the same spacing throughout a block.

Can Python indentation use tabs?

Python accepts tabs, but PEP 8 prefers spaces. Do not mix tabs and spaces in a file because ambiguous indentation can raise TabError.

How do I fix expected an indented block?

Indent at least one statement under the colon-ending header. If the block is intentionally empty for now, put an indented pass statement in it.

What causes unexpected indent in Python?

A line is indented where no open block allows that level. Remove the extra leading whitespace or place the line inside the intended suite.

Pankaj Kumar
Pankaj Kumar

I have been working on Python programming for more than 12 years. At AskPython, I share my learning on Python with other fellow developers.

Articles: 261