Advertisement
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
What makes BigCodeBench stand out from HumanEval? Explore how this new coding benchmark challenges models with complex, real-world tasks and modern evaluation
How Phi-2 is changing the landscape of language models with compact brilliance, offering high performance without large-scale infrastructure or excessive parameter counts
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
Discover how Nvidia continues to lead global AI chip innovation despite rising tariffs and international trade pressures.
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
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
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
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
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
Google debuts new tools and an agent protocol to simplify the creation and management of AI-powered agents.
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
IBM AI agents boost efficiency and customer service by automating tasks and delivering fast, accurate support.