Limited Offer
60% OFF on all plans!

Indentation Rules in Python

Understand how indentation works in Python. Learn why indentation is mandatory, how blocks are defined, common mistakes, and best practices.

Why Indentation Matters

Unlike many languages that use {} to define blocks, Python uses indentation (spaces at the beginning of a line). Indentation is not optional — it is part of Python syntax.

1. Indentation in if Statement

Indented code belongs to the block.

Indentation Defines Code Blocks

Every block in Python (if, for, while, function, class, etc.) must be indented consistently.

1. Indentation in Functions

Function body must be indented.

2. Indentation in Loops

Loop body must be indented.

Consistency in Indentation

Python requires consistent indentation. Mixing tabs and spaces can cause errors.

1. Correct Indentation (4 Spaces)

Recommended standard.

2. Indentation Error Example

Inconsistent indentation causes errors.

Nested Indentation

You can place one block inside another. Each new level increases indentation.

1. Nested if Example

Second block inside first block.

Common Indentation Mistakes

Indentation mistakes are very common for beginners because Python strictly enforces indentation.

1. Missing Indentation

Forgetting to indent after colon.

2. Unexpected Indentation

Indenting where not required.

Best Practices

Following these guidelines will prevent indentation errors and improve readability.

1. Recommended Guidelines

Industry standards.