Python Indentation Rules and Why They Matter
Indentation in Python means the spaces at the beginning of a line.
In many programming languages, blocks of code are grouped with braces like {}. Python works differently. It uses indentation to show which lines belong together.
This is why indentation is not just a style choice in Python. It is part of the language syntax.
If you are learning Python syntax, indentation is one of the first things to understand. It affects if statements, loops, functions, classes, and error handling blocks.
Quick example
if True:
print("Indented correctly")
for i in range(3):
print(i)
Use consistent spaces for code inside blocks. A common beginner rule is: indent each block with 4 spaces.
What indentation means in Python
Indentation is the space at the start of a line.
Python uses that space to decide which lines belong to the same block of code.
A block is a group of lines that run together under statements such as:
ifforwhiledefclasstry
Unlike some languages, Python does not use braces to define blocks. The indentation itself defines the block.
For example:
if 5 > 2:
print("This line is inside the if block")
print("This line is outside the if block")
What this code does
- The line with 4 spaces belongs to the
ifblock - The last
print()line is not indented, so it is outside the block
Output:
This line is inside the if block
This line is outside the if block
If you are new to Python structure, this idea also appears in Python if statements explained and Python functions explained.
Why indentation matters
Indentation matters because it tells Python where a block starts and ends.
This affects both correctness and meaning.
- It tells Python where a block starts and ends
- Wrong indentation can change program behavior
- Missing indentation can cause an error
- Inconsistent indentation makes code harder to read
Look at this example:
age = 18
if age >= 18:
print("Adult")
print("You can vote")
print("Done")
Here, both indented print() lines are part of the if block.
Now compare it to this:
age = 18
if age >= 18:
print("Adult")
print("You can vote")
The second version is valid Python, but it means something different. The last line is outside the if block, so it will run no matter what age is.
Small indentation changes can change how your program works.
Where indentation is required
Indentation is required after statements that introduce a block.
You will use it in places like these:
- After
if,elif, andelseblocks - Inside
forandwhileloops - Inside functions created with
def - Inside classes created with
class - Inside
try,except,else, andfinallyblocks
Here is a simple example with a loop:
for i in range(3):
print(i)
Output:
0
1
2
Without the indentation, Python does not know which line belongs to the loop.
If you want to learn these block types in more detail, see Python for loops explained and Python syntax basics explained.
The standard beginner rule
A simple rule for beginners is:
- Use 4 spaces for each indentation level
- Keep the same indentation style throughout a file
- Do not mix tabs and spaces
- Most code editors can insert 4 spaces automatically
This is the standard Python style and the easiest habit to follow.
Good example:
def say_hello():
print("Hello")
print("Welcome")
Less safe for beginners:
- Using tabs in one place
- Using spaces in another place
- Using 2 spaces on one line and 4 on another
Even if code looks aligned on your screen, Python may still see the indentation as different.
How indentation changes code meaning
Lines at the same indentation level belong to the same block.
A line indented further is nested inside another block.
A line moved back to the left ends the current block.
Here is an example:
for i in range(2):
print("Outer loop")
if i == 1:
print("Inner block")
print("Finished")
How Python reads this
print("Outer loop")is inside theforloopif i == 1:is also inside theforloopprint("Inner block")is inside both theforloop and theifblockprint("Finished")is outside all blocks
Output:
Outer loop
Outer loop
Inner block
Finished
This nesting is a basic part of Python program structure.
Common indentation errors beginners see
Beginners often see these errors:
IndentationError: expected an indented blockIndentationError: unexpected indentunindent does not match any outer indentation level
These usually happen:
- after a line ending with a colon
- when tabs and spaces are mixed
- when one line is indented more or less than Python expects
Example that causes an error:
if True:
print("Hello")
This raises an indentation error because the line after if True: must be indented.
Correct version:
if True:
print("Hello")
Another example:
if True:
print("Hello")
print("World")
This can raise an indentation error because the second print() line has a different indentation level that does not match the block structure.
If you are trying to fix a real error message, these pages can help:
- IndentationError: expected an indented block
- IndentationError: unexpected indent
- IndentationError in Python: causes and fixes
How to avoid indentation problems
You can prevent most indentation problems with a few habits:
- Use a code editor instead of a plain text editor
- Turn on visible whitespace if your editor supports it
- Use auto-formatting or reindent tools
- Check the line after statements ending with a colon
- If an error appears, compare the spaces on nearby lines
It also helps to type code yourself when learning, instead of only copy-pasting it.
If you do paste code from another source, check whether the indentation stayed consistent.
Common mistakes
These are the most common causes of indentation problems:
- Forgetting to indent after a colon
- Mixing tabs and spaces
- Indenting a line that should not be indented
- Using different numbers of spaces in the same block
- Copy-pasting code from different editors
For example, this is wrong because the second line should not be indented:
print("Start")
print("Wrong indent")
And this is wrong because the block uses inconsistent spacing:
if True:
print("Line 1")
print("Line 2")
A good debugging habit is to look at the lines just above and below the error location.
Useful commands for debugging
Run your file normally:
python your_file.py
You can also use Python's tabnanny tool to check indentation problems:
python -m tabnanny your_file.py
This can help detect inconsistent indentation, especially when tabs and spaces are mixed.
FAQ
How many spaces should I use for indentation in Python?
Use 4 spaces for each indentation level. This is the standard style and the easiest rule for beginners.
Can I use tabs instead of spaces in Python?
You can in some cases, but beginners should avoid tabs. Mixing tabs and spaces often causes indentation errors.
Why does Python care about indentation?
Python uses indentation to define blocks of code, such as the body of an if statement or loop.
What happens if indentation is wrong?
Python may raise an IndentationError, or the code may run with different logic than you expected.