Python Indentation: What It Is and Why It Matters
Python uses indentation instead of curly braces to define code blocks. Learn PEP 8's four-space rule, common IndentationErrors, and how to fix them.
Python uses indentation to define code blocks where C, C++, and Java use curly braces.
In every other mainstream language, indentation is cosmetic. In Python, it is syntax. Get it wrong and the interpreter raises an error before your code runs a single line. That makes indentation one of the first concepts to get right, and one of the most common sources of errors for students switching from C or C++.
What Python Indentation Does to Your Code
In Python, a block of code begins after a colon (:) and is defined by the level of indentation that follows. All statements at the same indent level belong to the same block. The block ends when the indentation returns to a lower level.
The Python Language Reference describes this through an indentation stack: the tokenizer tracks the current indentation level, and any increase opens a new block while any decrease closes the previous one.
Here is a simple example:
language = input("Enter a language: ")
if language.lower() == "python":
print("Correct")
else:
print("Not Python")
print("Done")
print("Correct")is indented one level inside theifblock.print("Not Python")is indented one level inside theelseblock.print("Done")is back at the base level and runs regardless of the condition.
Every if, else, elif, for, while, def, and class statement that ends with a colon requires at least one indented line to follow. A colon with no indented block below it raises:
IndentationError: expected an indented block
This error is among the first ones placement test auto-graders report. Understanding what triggers it saves debugging time on timed tests.
PEP 8: The Four-Space Standard
PEP 8, Python’s official style guide, specifies 4 spaces per indentation level. This is the default in VS Code and PyCharm, and the convention used on AMCAT Automata and TCS NQT Python coding sections. Code written to PEP 8 is immediately recognisable to any Python developer and easier to review in technical interviews.
The critical rule is consistency. Python does not require exactly 4 spaces; it requires that every line inside the same block uses the same number of spaces. The following is syntactically valid Python:
if True:
print("two spaces -- works")
print("still two spaces -- same block")
But mixing different indentation widths inside the same block:
if True:
print("four spaces")
print("two spaces here")
raises IndentationError: unexpected indent because the interpreter sees the second line at a different level than the first.
Tabs vs. Spaces
Python 3 raises TabError: inconsistent use of tabs and spaces in indentation if you mix tab characters and space characters within the same file. Python 2 allowed this (it treated a tab as 8 spaces), but Python 3 made the behaviour strict.
The practical rule: configure your editor to insert 4 spaces when you press Tab. Both VS Code and PyCharm do this by default for Python files. On the command line, python3 -tt your_file.py turns tab-space inconsistency into a hard error rather than a silent issue.
Nested Indentation: Multiple Levels
When code contains loops or conditions inside other loops or conditions, each nesting level adds one more indent level. Each level is 4 spaces wider than its parent.
numbers = [1, 2, 3, 4, 5]
for n in numbers:
if n % 2 == 0:
print(n, "is even")
else:
print(n, "is odd")
- The
forblock is at indent level 1 (4 spaces from the left margin). - The
ifandelseblocks are at indent level 2 (8 spaces). printstatements insideifandelseare at indent level 3 (12 spaces).
The body of the loop, the condition, and the print statements each belong to a different block. Missing a level of indentation anywhere in this structure produces an IndentationError. In placement tests, nested for loops with conditions inside them are a common pattern in array traversal problems, for instance in problems that ask you to find the smallest and largest element in an array using a scanning loop with a conditional update inside.
Common IndentationErrors and How to Fix Them
IndentationError: expected an indented block
This occurs when a colon appears with no indented statement below it.
if True:
print("No indentation here") # Error
- The interpreter reaches the colon, expects the next line to be at a deeper indent level, and finds a line at the same level instead.
- Fix: add 4 spaces before
print("No indentation here").
IndentationError: unexpected indent
This occurs when a line is indented without a preceding colon that opened a block.
print("Start")
print("Unexpected") # Error
- No block was opened; the indented line has no parent block to belong to.
- Fix: remove the extra indentation from the second
print.
The third common error is TabError: inconsistent use of tabs and spaces. This only surfaces when both tab characters (inserted by pressing Tab in an editor not configured for Python) and space characters coexist in the same file. The fastest fix is to run the editor’s “Convert Indentation to Spaces” command and set the tab size to 4, then resave.
The palindrome string check in Python is a good follow-up problem to test this. It uses if-else and for-loop nesting at two indent levels, making IndentationErrors immediately visible if the indentation is off.
Tools That Catch Indentation Problems Before You Run
Several tools surface indentation errors before code executes:
| Tool | What it does |
|---|---|
| VS Code with Pylance | Underlines indentation errors in real time as you type |
| PyCharm | Highlights mixed tabs/spaces; offers one-click auto-fix |
| flake8 | Command-line linter; E1xx error codes cover indentation issues |
| autopep8 | Auto-corrects PEP 8 violations including indentation style |
Running python3 -tt your_file.py on the command line is a quick check on machines where a full IDE is not available. The -tt flag escalates tab-space inconsistency from a warning to an error, making it easy to catch during practice sessions on contest platforms.
Python’s indentation rule catches students who come from C or C++ backgrounds, usually on the first or second attempt at writing a multi-block program. After two or three IndentationErrors, the 4-space habit becomes automatic. Clean indentation is also the same habit that makes code readable during technical interviews at placements, where reviewers at service-tier companies (TCS, Infosys, Wipro) and product-company interviewers both look at structure and readability alongside correctness.
Getting this right early makes every Python program easier to debug, extend, and review. For students working through broader technical interview prep, the 20 most asked DSA interview questions covers the data structure patterns that appear most often in placement coding rounds.
The clean-code instinct that Python indentation builds, consistent structure, clear block boundaries, no invisible whitespace surprises, carries directly into Python-based LLM scripts and AI workflows. If you want to apply that instinct to actual LLM projects, TinkerLLM starts at ₹299 and runs entirely in Python.
Primary sources
Frequently asked questions
Is indentation mandatory in Python?
Yes. Python uses indentation to define code blocks. Omitting it after if, for, while, def, or class raises IndentationError: expected an indented block.
How many spaces does PEP 8 recommend for Python indentation?
Four spaces per indentation level. This is the default in VS Code and PyCharm and the standard enforced by most team linters and placement coding platforms.
Can I use tabs instead of spaces in Python?
You can, but PEP 8 recommends spaces. In Python 3, mixing tabs and spaces in the same file raises TabError at runtime. Pick one and use it throughout the file.
What is IndentationError in Python?
An IndentationError occurs when the Python interpreter finds unexpected or missing indentation. The two most common forms are: expected an indented block (you forgot to indent after a colon) and unexpected indent (you indented a line that should not be indented).
Why does Python use indentation instead of curly braces?
Python's design philosophy, outlined in PEP 20, favours readability. Indentation makes the block structure visually obvious without extra punctuation, reducing the chance of mismatched braces and making code easier to scan.
How do I detect mixed tabs and spaces in my Python file?
Run python3 -tt your_file.py. The -tt flag turns tab-space inconsistency warnings into errors. VS Code and PyCharm also highlight mixed whitespace before you run the file.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)