Python Syntax & Indentation: How Blocks and Whitespace Work
Python uses indentation to show which statements belong together, so whitespace is part of the language syntax, not just formatting. A colon starts a block, and the indented lines after it are the body of that block. This article shows how Python reads indentation, how to write blocks correctly, and how to avoid the errors that beginners hit most often.
Difficulty: Beginner
Helpful to know first: basic Python variables, print statements, and simple if statements will make the examples easier to follow.
How Python Uses Indentation to Form Blocks
In Python, a block is a group of statements that belong to the same control structure, such as an if statement, a for loop, a while loop, a function, or a class. Unlike many languages that use braces like { and }, Python uses indentation to show the start and end of a block.
The rule is simple: when a line ends with a colon, the next indented lines belong to that block. When the indentation decreases, the block ends. Python reads this structure directly, so indentation must be consistent.
age = 20
if age >= 18:
print("Adult")
print("You can vote in many places.")
print("Done")
# Output:
# Adult
# You can vote in many places.
# DoneHere, the two indented print() calls are inside the if block. The last print() is not indented, so it runs after the block finishes.
Writing the Smallest Valid Python Block
A block does not need many lines. Even a one-line body is valid if it is indented correctly. This is the minimum pattern you will see again and again in Python.
if 3 > 2:
print("Three is greater than two.")
# Output:
# Three is greater than two.The colon ends the header line, and the indented statement becomes the body. If you remove the indentation, Python no longer sees a valid block.
Indentation in if Statements, Loops, and Functions
Indentation works the same way in every compound statement. The visible shape of the code tells you what is nested inside what, which makes Python code readable when it is written well.
Indentation in a loop
Every line inside the loop body must be indented. Anything aligned with the for line is outside the loop.
for number in range(3):
print("Loop value:", number)
print("Loop ended")
# Output:
# Loop value: 0
# Loop value: 1
# Loop value: 2
# Loop endedThe loop body runs three times. The final print() is outside the loop because it is not indented.
Indentation in a function
Function definitions also use indentation. The function body starts after the colon, and every line in the function must stay indented under the def line.
def greet(name):
print("Hello,", name)
print("Welcome!")
greet("Mina")
# Output:
# Hello, Mina
# Welcome!Without indentation, Python would not know which lines belong to the function body.
Nested blocks
You can indent inside an indented block to create a nested block. Each level of indentation means one deeper level of nesting.
score = 85
if score >= 50:
print("Passed")
if score >= 80:
print("Excellent")
# Output:
# Passed
# ExcellentPython does not count blocks by braces. It counts them by indentation level.
How Python Decides Where a Block Starts and Ends
Python uses the colon as a cue that a block is coming, but the indentation itself defines the block. A colon alone does nothing unless the next logical line is indented correctly.
The interpreter checks the indentation level at the start of each line. When the indentation increases after a colon, that begins a block. When the indentation decreases, the previous block ends. If the indentation changes in a way Python does not expect, you get an error.
Python also treats indentation as part of the program structure, not as visual decoration. That means two lines that look similar to you may mean different things to Python if their indentation is different.
Python accepts any consistent indentation style, but PEP 8 recommends 4 spaces per indentation level. Most Python editors can insert spaces automatically when you press Tab.
Spaces, Tabs, and Why Mixing Them Causes Trouble
Python supports indentation with spaces or tabs, but mixing them in the same file is risky. The best practice is to use spaces only, and most modern Python code uses four spaces per level.
A tab may look like four spaces in your editor, but Python may interpret it differently. If one line uses tabs and another uses spaces, the code can become inconsistent even when it appears lined up on screen.
# Good: four spaces per level
if True:
print("Using spaces")
# Avoid mixing tabs and spaces in the same blockIf you are using an editor, turn on visible whitespace or auto-formatting. That makes indentation problems much easier to spot before you run the program.
Why Python Has Indentation Instead of Braces
Python chose indentation to make code structure visible and consistent. Because every block must be indented, the code tends to read like an outline. That makes nested logic easier to follow when the code is written carefully.
The trade-off is that whitespace now matters. A misplaced space can change the meaning of the program or produce a syntax error. In brace-based languages, extra spaces usually do not matter much. In Python, they can matter a lot.
This design is one reason Python code often looks cleaner than code in languages with lots of punctuation. It is also why beginners need to treat formatting as part of writing correct code, not as a final cleanup step.
How Indentation Affects Readability and Control Flow
Indentation shows control flow, which is the order and nesting of actions in your program. When code is indented well, you can scan it quickly and see what runs inside a branch, inside a loop, or inside a function.
Bad indentation can make code hard to understand even when it is technically valid. For example, a line may look like it belongs to an if block when it actually does not. That kind of mistake often causes logic bugs, not syntax errors.
logged_in = True
if logged_in:
print("Welcome back")
print("This runs no matter what")
# Output:
# Welcome back
# This runs no matter whatThe second print() is outside the if block because it is aligned with the if line, not indented under it. Beginners often assume it is still part of the branch because it appears close to the previous line.
Common Mistakes with Python Syntax and Indentation
Forgetting to indent after a colon
After a line that ends with a colon, Python expects an indented block. If you forget the indentation, the interpreter stops with a syntax error.
Problem: The block header is correct, but the body is not indented, so Python cannot tell where the block starts.
if 5 > 3:
print("Five is larger")Fix: Indent the body by one level.
if 5 > 3:
print("Five is larger")The corrected version works because Python can now see the indented statement as the block body.
Indenting one line too far or too little
Every line in the same block must line up exactly. If one line has a different indentation level, Python may treat it as a new block or raise an indentation error.
Problem: The second line inside the loop is not aligned with the first line, so the block is inconsistent.
for item in [1, 2, 3]:
print(item)
print("Next")Fix: Keep both statements at the same indentation level if they belong to the loop.
for item in [1, 2, 3]:
print(item)
print("Next")The fixed version works because both statements are clearly part of the same loop body.
Mixing tabs and spaces in one file
Some editors insert a tab character when you press Tab, while others insert spaces. Mixing the two can produce errors that are hard to spot by eye.
Problem: The code may look aligned in your editor, but Python sees different indentation characters and can raise a tab-related indentation error.
if True:
print("Spaces here")
print("Tab here")Fix: Use spaces consistently, preferably four per level.
if True:
print("Spaces here")
print("Tab removed")The corrected version works because the indentation is consistent and easy for Python to interpret.
Putting code at the wrong indentation level
This mistake does not always cause a syntax error. Sometimes it changes the program logic instead, which can be harder to notice.
Problem: The last line should run only when the condition is true, but it is not indented, so it runs every time.
temperature = 30
if temperature >= 25:
print("It's hot")
print("Take water")Fix: Indent every statement that belongs inside the branch.
temperature = 30
if temperature >= 25:
print("It's hot")
print("Take water")The corrected version works because both lines are now inside the same decision block.
Predict the Output
What prints after the loop ends?
total = 0
for number in range(3):
total += number
print(total)What does this print?
Show answer
The output is 3. The loop adds 0, then 1, then 2. After the loop ends, total is 3, and the final print() runs once.
# Output:
# 3Which lines are inside the condition?
x = 4
if x % 2 == 0:
print("even")
print("done")What happens?
Show answer
It prints even and then done. The first print() is inside the if block. The second line is not indented, so it runs after the condition finishes, no matter what the condition is.
# Output:
# even
# doneFind the Bug
This code looks reasonable, but it has a subtle indentation problem. Find the line that is in the wrong place.
def countdown(start):
for number in range(start, 0, -1):
print(number)
print("Done")
countdown(3)Show answer
The bug is that print("Done") is indented only one level, so it is inside the function but outside the loop. That means it runs once after the loop finishes. If the goal is to print Done after all numbers, this is correct. If the goal is to print it after every number, it needs to be indented inside the loop.
Here is the version that prints Done once after the loop, which matches the current structure:
def countdown(start):
for number in range(start, 0, -1):
print(number)
print("Done")
countdown(3)
# Output:
# 3
# 2
# 1
# DoneTry It Yourself
Write a small program that uses indentation to show a menu choice.
- Create a variable named choice and set it to "tea".
- Use an if statement to check whether the choice is "tea".
- If it is, print "Hot tea selected".
- Then print "Order complete" only after the condition block ends.
Expected output:
# Hot tea selected
# Order completeHint: The second message should not be indented under the if statement.
Show solution
choice = "tea"
if choice == "tea":
print("Hot tea selected")
print("Order complete")When to Use Indentation Carefully, and When to Watch for Other Tools
Indentation is not optional in Python, so the main question is not whether to use it. The real question is how to manage it reliably. For simple scripts, manual indentation is fine if you stay consistent. For larger programs, editor formatting and linting become more important.
| Situation | What to do | Why |
|---|---|---|
| Small beginner script | Use 4 spaces per level | Matches Python style and keeps blocks easy to read |
| Team project | Use an autoformatter or editor settings | Prevents mixed indentation and style drift |
| Nested logic | Keep blocks short and clear | Makes control flow easier to follow |
| Debugging syntax errors | Check the line above the error first | Indentation mistakes often appear on the previous line |
Indentation is a syntax rule, but it also acts like documentation. Good indentation tells the reader how your code works before they run it.
Interview Questions
Why does Python use indentation instead of braces?
Python uses indentation to make block structure part of the language itself. This encourages readable code and reduces extra punctuation, but it also means whitespace must be consistent.
How many spaces should Python indentation use?
The usual style is 4 spaces per indentation level. That is the standard recommendation in PEP 8 and the most common style in real Python code.
What is the difference between syntax errors and logic errors in indentation?
A syntax error means Python cannot parse the structure of the code, often because a block is missing or misaligned. A logic error means the code still runs, but the indentation makes it do the wrong thing.
Summary
- Python uses indentation, not braces, to define blocks.
- A line ending in a colon usually starts a block.
- Lines inside the block must be indented consistently.
- Four spaces per level is the standard Python style.
- Mixing tabs and spaces can cause hard-to-find errors.
- Wrong indentation can change program logic even when the code still runs.
Next, learn Python if statements and how they use indentation to control which code runs.