Understanding Indentation in Python with Examples

Advertisement

Jun 04, 2025 By Alison Perry

Learning Python often feels different from other languages right from the start. One of the biggest shifts is how it handles indentation. It's not a choice or a style—it's required. Python won't run unless everything is lined up correctly. That might seem harsh initially, especially if you're used to curly braces or semicolons doing the work.

But once you get it, this system begins to make sense. Indentation becomes a part of how you approach code organization. It keeps things tidy and makes it easier to see mistakes. Let's run through what it is, how it works, and some examples so it is easier to understand.

What is Indentation in Python?

Indentation is spaced at the beginning of a line. In Python, the spaces indicate which lines go together. They inform the program which lines are in a loop, a function, or a condition. Python cannot know where one block stops and the next starts without it.

Other languages often use symbols like curly braces to group code. Python skips the braces and uses spacing instead. If the spacing is off, the interpreter won’t run the code. It throws an error right away.

Every time you write something that controls a group of lines—like a loop, a condition, or a function—you need to follow it with an indented block. That block must be lined up consistently. If it’s not, Python won’t understand it.

Basic Indentation Rules in Python

There are a few simple things to remember when working with indentation in Python. They're easy enough to remember once you've seen them in action.

Consistent Spacing

Python uses spaces to structure code. The usual standard is four spaces per level. You can use tabs, but it’s better to stick with spaces. Most editors do this by default. If you mix tabs and spaces, Python will throw an error. So, pick one style and stick with it. Four spaces are the most common and widely accepted.

Aligned Code Blocks

Every line inside the same block must have the same spacing. If one line is off by even a single space, Python sees it as part of a different block or gives you an error.

if True:

print("First line")

print("Second line")

Both print statements have the same number of spaces. They’re treated as part of the same condition.

Required After Block Headers

Any time you use a line that controls the flow—like if, for, while, def, or class—a block must follow it. That block has to be indented. If you forget, the interpreter stops right there.

for i in range(3):

print(i)

The line under the for statement is indented. That tells Python it belongs to the loop.

Nested Blocks Add Layers

When you put one block inside another, each level adds more indentation. This shows how deep the structure goes.

if True:

for i in range(2):

print(i)

Each deeper level adds more space. It helps organize the code visually and tells Python how to group the statements.

Empty Blocks Use pass.

If you're setting up something without filling it in, you can't just leave it blank. Python expects something inside, so use the pass as a placeholder.

def later():

pass

It does nothing, but it keeps the interpreter happy.

Indentation Examples

Now, let's review a few examples that show how indentation works in different cases. These will give you a better sense of what to expect and how to structure your code.

Function Definition

def greet(name):

print("Hello,", name)

print("Welcome!")

Both print lines are part of the greet function. They sit one level inside it. Each line starts with four spaces.

Conditional Structure

age = 20

if age >= 18:

print("Adult")

else:

print("Minor")

Here, the if and else lines are at the same level. Each block under them is indented equally, keeping the condition clear and readable.

Loop with Conditional Check

for num in range(4):

if num % 2 == 0:

print(num, "is even")

else:

print(num, "is odd")

There's a loop and a condition inside it. Each block is one level deeper than the last. This shows which lines belong where they do not need extra symbols.

Multiple Levels

def check(n):

if n > 0:

print("Positive")

if n > 10:

print("Large number")

else:

print("Zero or negative")

The function has one level of indentation. Inside that, the first condition adds another. Then, the second condition adds a third. This layering keeps the logic tidy and clear.

Wrong Indentation

Here’s what not to do:

def broken():

print("Line one")

print("Line two") # Too many spaces

This will throw an error. The second line doesn't match the first. Even if it looks fine, the interpreter checks the spacing exactly.

Another bad example:

if True:

print("Missing space")

This won’t run either. The line after the if needs to be indented.

Avoiding Errors

Most modern code editors help with indentation. They'll automatically insert the right number of spaces when you hit Enter. Still, it's good to watch, especially if you copy and paste code. Make sure everything lines up.

If you ever get an IndentationError or TabError, the issue is usually spacing. Check the lines above and below where the error occurs. Ensure the blocks are all aligned, and you haven't mixed tabs and spaces.

Conclusion

Python's indentation rule might initially seem strict, but it has a purpose. It keeps code easy to read and maintain. Writing clean code becomes easier once you understand how blocks are structured and how spacing controls that structure. Every line matters. Spacing isn't just about appearance—it's about function. You don't need extra syntax to mark code blocks. Just line things up correctly, and Python takes care of the rest. With a little practice, it starts to feel natural. Mistakes with indentation are usually simple to fix, and the more you write, the quicker it becomes second nature.

Advertisement

Recommended Updates

Technologies

BigCodeBench Raises The Bar For Realistic Coding Model Evaluation Metrics

What makes BigCodeBench stand out from HumanEval? Explore how this new coding benchmark challenges models with complex, real-world tasks and modern evaluation

Applications

Compact Brilliance: How Phi-2 Is Changing Language Model Design

How Phi-2 is changing the landscape of language models with compact brilliance, offering high performance without large-scale infrastructure or excessive parameter counts

Applications

Which AI Assistant Wins in 2025? Comparing ChatGPT and HuggingChat

Compare ChatGPT vs. HuggingChat to find out which AI chatbot works better for writing, coding, privacy, and hands-on control. Learn which one fits your real-world use

Technologies

Explore How Nvidia Maintains AI Dominance Despite Global Tariffs

Discover how Nvidia continues to lead global AI chip innovation despite rising tariffs and international trade pressures.

Technologies

Top 5 Compelling Reasons to Switch from VLOOKUP to INDEX MATCH in Excel

Why INDEX MATCH is often a better choice than VLOOKUP in Excel. Learn the top 5 reasons to use INDEX MATCH for more flexible, efficient, and reliable data lookups

Impact

Voices That Matter: 12 Data Science Leaders Worth Following in 2025

Discover the top data science leaders to follow in 2025. These voices—from educators to machine learning experts—shape how real-world AI and data projects are built and scaled

Technologies

Mastering the Python strftime() Function for Date Formatting

Explore the Python strftime() function and how it helps convert datetime objects into formatted strings. Learn common usage, tips, and avoid pitfalls in this detailed guide

Basics Theory

Choosing Between Alpaca and Vicuna: Which LLM Performs Better

Curious about Vicuna vs Alpaca? This guide compares two open-source LLMs to help you choose the better fit for chat applications, instruction tasks, and real-world use

Applications

AI Image Enhancers That Actually Work: 10 Top Picks for 2025

Looking for the best AI image enhancers in 2025? Discover 10 top tools that improve image quality, sharpen details, and boost resolution with a single click

Applications

Google Launches Tools and Protocol for Building AI Agents

Google debuts new tools and an agent protocol to simplify the creation and management of AI-powered agents.

Technologies

How to Use Permutation and Combination in Python

How to use permutation and combination in Python to solve real-world problems with simple, practical examples. Explore the built-in tools and apply them in coding without complex math

Technologies

What Benefits Do IBM AI Agents Bring to Businesses?

IBM AI agents boost efficiency and customer service by automating tasks and delivering fast, accurate support.