Indentation in Python (With Examples)

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.

Python uses indentation — not braces or keywords — to group statements into logical code blocks. Every function, loop, class, and conditional in Python depends on consistent indentation to work correctly. Get it wrong and Python throws an IndentationError immediately. This guide covers the rules, common mistakes, and how to avoid indentation-related bugs in your code.

Indentation in Python refers to the whitespace at the start of a line that tells Python which block a statement belongs to. Blocks are groups of code that run together — like the body of an if statement or the statements inside a for loop. Python requires you to indent those statements uniformly, typically using 4 spaces per level. This is different from languages like C, C++, and Java that use curly braces {} to define blocks. Let’s walk through everything you need to know to use indentation correctly.

What is Indentation in Python?

Indentation in Python refers to the whitespaces at the start of a line that indicate a block of code. Python uses indentation where other languages use braces { }. When you write a function, loop, or conditional statement, the lines that “belong” to it must be indented consistently.

The leading whitespaces (spaces or tabs) at the start of a line determine the indentation level. You increase the indent level to open a new block and decrease it to close one. Python’s official style guide (PEP 8) recommends using 4 spaces per indentation level.

Here’s a complete example showing indentation in action:

def foo():
    print("Hi")

    if True:
        print("true")
    else:
        print("false")

print("Done")

Python Indentation
Python Indentation

Python vs Other Languages: A Quick Comparison

Most mainstream programming languages use braces { } to define code blocks. Python takes a different approach — it uses indentation. Here’s how they compare:

FeaturePythonC / C++ / Java / JavaScript
Block delimiterIndentation (spaces/tabs)Curly braces { }
EnforcementPython interpreter requires itBraces required, whitespace ignored
Style guidePEP 8 recommends 4 spacesCommonly 4 spaces or 2 spaces
Mixing tabs and spacesAllowed but discouragedIrrelevant (braces do the grouping)
ReadabilityForced clean code structureFlexible but easy to write messy code

Python Indentation Rules

Follow these rules to write valid Python code:

  • The first line of a Python file cannot have indentation — it will raise IndentationError.
  • Never mix tabs and spaces. Use one or the other consistently throughout your file.
  • PEP 8 recommends using 4 spaces per indentation level — stick to this for best results.
  • All statements within the same block must have the same indentation level.
  • You must indent the body of functions, loops, conditionals, classes, and context managers.
  • Python raises IndentationError: expected an indented block if you leave a block empty without a pass statement.

Benefits of Indentation in Python

  • Readability: Indentation makes the code hierarchy immediately visible — you can see at a glance which statements belong together.
  • No delimiters needed: Unlike C or Java, you don’t need braces for basic block grouping — Python handles it through whitespace.
  • Consistency: All Python code follows the same indentation rules, making it easier to read and maintain.
  • Built-in beauty: Python’s indentation requirement forces you to write well-structured, clean-looking code.
  • IDE support: Nearly every Python IDE and code editor auto-indents for you, so writing properly indented code is nearly effortless.

Disadvantages of Indentation in Python

  • Copy-paste issues: Copying code from PDFs, Word documents, or poorly formatted websites can corrupt indentation and cause hard-to-debug errors.
  • Learning curve: Developers coming from brace-based languages need time to adjust to whitespace-based grouping.
  • Hidden errors: If a block’s indentation gets accidentally broken in a large file, finding it can be tedious.

Indentation in a Python for Loop

All statements inside a for loop must be indented to belong to that loop’s block. Here’s an example:

def print_numbers(x, y):
    for i in range(x, y):
        print(i)

The print(i) line is indented under the for loop, so it runs for each iteration. The function definition itself is at the top level (no indentation), and the for line is indented once inside the function.

Common IndentationError Examples

Here are the most frequent indentation errors and how to fix them.

Example 1: Indentation on the first line

>>>     x = 10
  File "", line 1
    x = 10
    ^
IndentationError: unexpected indent

The first line of a file or code block cannot be indented. Python throws IndentationError: unexpected indent because there’s no preceding block to justify the indentation.

Example 2: Inconsistent indentation inside a block

if True:
    print("true")
     print("Hi")   # extra space — inconsistent!
else:
    print("false")

All lines inside an if block must use the same indentation level. The second print("Hi") has an extra space, so Python raises an indentation error.

Example 3: Orphaned indentation (nothing to attach to)

if True:
    print("true")
else:
    print("false")

 print("Done")   # indented but no block above it!

Python raises IndentationError here because the final print("Done") is indented but has no parent block — it doesn’t belong to anything above it.

Example 4: Missing indentation inside a block

if True:
print("true")   # missing indentation!
else:
print("false")  # missing indentation!

Python raises IndentationError: expected an indented block because the bodies of the if and else statements are not indented.

Fix for empty blocks: If you need a block that does nothing, use the pass statement:

if True:
    pass   # do nothing
else:
    print("false")

Frequently Asked Questions (FAQ)

How many spaces should I use for Python indentation?

Use 4 spaces per indentation level, as recommended by PEP 8 — Python’s official style guide. This is the most widely adopted convention in the Python community.

Can I use tabs instead of spaces in Python?

Yes, Python accepts tabs, but mixing tabs and spaces causes subtle bugs that are hard to debug. Stick to spaces for consistency across all editors and tools.

Why does Python use indentation instead of braces?

Guido van Rossum, Python’s creator, chose indentation-based grouping because it enforces readable code by design. It removes the option to write messy, poorly structured code that compiles but is hard to maintain.

What is IndentationError in Python?

IndentationError is raised when Python encounters a line with incorrect or unexpected indentation. Common causes include mixing tabs and spaces, leaving a block empty without pass, or inconsistent indentation within the same block.

How do I fix an unexpected indent error?

Check that the offending line doesn’t have extra spaces or tabs at the beginning compared to surrounding lines. Use a code editor that shows hidden whitespace characters, or run python -t to get warnings about inconsistent tab/space usage.

What is the pass statement used for in indentation?

pass is a null operation used as a placeholder when a block can’t be empty. For example, if you have an if statement that intentionally does nothing yet, write pass inside its body to avoid an IndentationError.

Does Python 3 require indentation?

Yes. In Python 3, all code blocks inside functions, loops, conditionals, classes, and context managers must be indented. Unlike some languages where it’s optional, omitting indentation in Python is a syntax error.

Summary

Indentation in Python is not optional — it’s a core part of the language syntax. It groups statements into blocks and determines the structure of your program. Use 4 consistent spaces per indentation level, never mix tabs and spaces, and always indent the body of functions, loops, and conditionals. If you need an intentionally empty block, use the pass statement. Following these rules will help you avoid IndentationError entirely and write clean, readable Python code.

Related Python Topics

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: 242