Indentation in Python
This article discusses indentation in Python, a core concept that defines code blocks and program structure. It covers what indentation is, Python indentation rules, and the benefits of proper indentation, helping learners write clean, readable, and professional Python code.
What is Indentation in Python
Indentation in Python refers to the spaces or tabs at the beginning of a line of code. Unlike many other programming languages that use braces {} to define blocks of code, Python uses indentation to determine the structure and hierarchy of the program.
Get Saurabh Gandhi’s stories in your inbox
Join Medium for free to get updates from this writer.
In Python, indentation tells the interpreter which statements belong to the same block, such as inside loops, conditions, functions, or classes.
In simple words: Indentation = how Python understands blocks of code
Python Indentation Rules
Python has strict indentation rules. If you break them, Python will raise an error.
1. Consistent indentation is mandatory
- Use either spaces or tabs, but never mix them
- Recommended: 4 spaces per indentation level (PEP 8 standard)
2. Indentation starts a block
A block begins after statements like:
- if
- for
- while
- def
- class
- try
3. All statements in the same block must have the same indentation
- Even one extra or missing space causes an error
4. No indentation = outside the block
- Code without indentation runs independently of blocks
5. Incorrect indentation raises errors
Common errors:
- IndentationError
- TabError
6. Empty Blocks Require pass
- Without
pass, Python throws an error.
Benefits of Indentation in Python
Indentation is not just a rule — it’s a feature that improves code quality.
- Improves code readability
- Code structure is visually clear
- Easy to understand logic flow
2. Enforces clean and consistent code
- Encourages good coding practices
- Reduces messy or deeply nested code
3. Eliminates unnecessary symbols
- No need for {} or end keywords
- Cleaner and shorter syntax
Disadvantages of Indentation
- Beginners may get errors
- Copy-paste issues
- Mixing tabs/spaces causes problems
- One missing space can break code
Example
here are simple, clear indentation examples
1. Basic If Condition
# ✅ Correct Indentation
x = 10
if x > 5:
print("X is grater than 5")# ❌ Incorrect Indentation
x = 10
if x > 5:
print("X is grater than 5")2. For Loop Example
# ✅ Correct Indentation
for i in range(3):
print("Number:", i)# ❌ Incorrect Indentation
for i in range(3):
print("Number:", i)Best Practices for Indentation
- Always use 4 spaces
- Never mix tabs and spaces
- Configure your editor to insert spaces automatically
- Keep consistent indentation across project
Questions
- What is indentation in Python?
- Why is indentation important in Python?
- How many spaces are recommended for indentation in Python?
- What error occurs when indentation is incorrect?







