Python uses indentation — the spaces at the start of a line — to define the structure of your code. If you are coming from another language, or if this is your first language altogether, indentation is the single concept you need to understand before anything else will make sense.
In many programming languages, you use curly braces {} to mark where a block of code begins and ends. Python takes a different approach: the block is defined entirely by how far the lines are pushed in from the left margin. This is not a style suggestion — it is a rule enforced by the interpreter at runtime. Get the spacing wrong and Python raises an IndentationError before your program even starts.
What Indentation Actually Does in Python
When Python reads your source file it looks at the leading whitespace — the spaces before the first non-space character on each line — to group lines into blocks. A block is a set of statements that belong together: the body of a function, the body of a loop, the branch of an if statement. Every time you write a statement that opens a block, you end it with a colon and then indent the lines that belong to it.
Python tracks a stack of indentation levels. When a new line is more indented than the previous one, Python pushes a new block onto the stack. When it is less indented, Python pops blocks off the stack until it finds a matching level. A line that does not match any level on the stack is an IndentationError.
The standard unit of indentation in Python is 4 spaces. This is the recommendation of PEP 8, the official Python style guide, and every widely used Python project follows it. Your editor's Tab key can be configured to insert 4 spaces automatically — and in most Python-aware editors it is set that way by default.
Python 3 raises a TabError if your file mixes tab characters and space characters for indentation. Choose spaces and stay consistent throughout the file. Configure your editor to expand Tab key presses into spaces so the problem never arises.
The following example shows a complete function. The two lines inside the function are indented by 4 spaces. The print call after the function is at zero indentation and is therefore not part of the function body.
def greet(name):
message = "Hello, " + name # 4 spaces — inside the function
return message # 4 spaces — still inside the function
print(greet("Kandi")) # 0 spaces — outside the function
If you removed the indentation from the return line and brought it back to zero, Python would raise a SyntaxError because a return statement outside a function is invalid. If you indented it by 3 spaces instead of 4, Python would raise an IndentationError because 3 does not match the 4-space level opened by the def.
Build the correct function definition header line by clicking each token in order:
Indentation in Functions, Loops, and Conditionals
The same rule applies everywhere a block is needed. Functions, for loops, while loops, if/elif/else chains, with statements, try/except blocks, and class definitions all use the colon-then-indent pattern. The examples below show each case with the indented lines highlighted.
Conditional blocks
score = 72
if score >= 90:
grade = "A" # 4 spaces — the if block
elif score >= 70:
grade = "B" # 4 spaces — the elif block
else:
grade = "C" # 4 spaces — the else block
print(grade) # 0 spaces — after all branches
For loop body
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
upper = fruit.upper() # 4 spaces — inside the loop
print(upper) # 4 spaces — still inside the loop
print("Done.") # 0 spaces — the loop has ended
In VS Code, PyCharm, and most editors, pressing Tab inside a Python file inserts 4 spaces. Shift+Tab removes 4 spaces. You can select multiple lines and Tab/Shift+Tab to indent or dedent the whole selection at once.
- Syntax
def function_name(parameters):- Block content
- All statements that make up the function body, indented 4 spaces.
- Syntax
if condition:followed by indented body; optionalelif condition:andelse:at the same level asif.- Block content
- Each branch has its own indented block. All branches sit at the same indentation level.
- Syntax
for item in iterable:orwhile condition:- Block content
- Every statement that repeats with the loop, indented 4 spaces from the loop header.
- Syntax
try:followed by indented body;except ExceptionType:at the same level astry, with its own indented body.- Block content
- The code that might raise an error goes in the
tryblock. Recovery code goes in theexceptblock.
This function should print a greeting but it raises an IndentationError. Click the line you think is wrong, then hit check.
Nested Indentation and Visual Structure
Nesting happens when one block is placed inside another — for example, an if statement inside a for loop, or a loop inside a function. Each level of nesting adds another 4 spaces. The result is a visual staircase that lets you read the program structure at a glance.
def check_scores(scores): # 0 spaces — top level
for score in scores: # 4 spaces — inside function
if score >= 90: # 8 spaces — inside the loop
print("Excellent") # 12 spaces — inside the if
elif score >= 70: # 8 spaces — same level as if
print("Pass") # 12 spaces — inside elif
else: # 8 spaces — same level as if
print("Needs work") # 12 spaces — inside else
check_scores([95, 73, 55]) # 0 spaces — back at top level
Notice how the elif and else keywords line up exactly with the if that started the chain. They are not inside the if block — they are continuations of the same conditional statement, so they sit at the same 8-space level. Only the code inside each branch is pushed in by another 4 spaces.
"Code is read more often than it is written." — Guido van Rossum, creator of Python
How to Write Correctly Indented Python Code
Follow these five steps every time you open a new block in Python and you will avoid the vast majority of indentation errors before they happen.
-
Configure your editor for 4-space indentation
Open your editor settings and set the indent size to 4 spaces. Turn off the option that inserts a real tab character so your editor inserts four space characters every time you press Tab. In VS Code this is
editor.tabSize: 4andeditor.insertSpaces: true. -
End the header line with a colon
Every block-opening statement —
def,if,elif,else,for,while,with,class,try,except,finally— must end with a colon. The colon tells Python that an indented block follows. A missing colon raises aSyntaxError. -
Indent all lines inside the block by exactly 4 spaces
Every line that belongs to the block must start with the same number of leading spaces. Inside a function, that is 4 spaces. Inside a loop inside the function, that is 8 spaces, and so on. A line that is even one space off from the rest of the block will cause an
IndentationError. -
Return to the outer level to end the block
There is no closing brace or
endkeyword. Simply write the next line at the original indentation level and Python knows the block has ended. If you are inside a function and want to write code that runs after the function is called, bring it back to 0 spaces. -
Run the file and read any IndentationError message carefully
If Python raises an
IndentationError, it will tell you the file and line number. Look at that line, compare its leading spaces to the lines above it, and correct the mismatch. The error message often includes the text "expected an indented block" or "unexpected indent" — both point to a level-mismatch problem.
This loop should print every number from 1 to 3 with a label, but one line is indented incorrectly. Click the buggy line and hit check.
label and print() are inside the same for loop body, so they must share the same indentation level of 4 spaces. Line 4 was over-indented by an extra 4 spaces, suggesting to Python that it is inside a nested block that does not exist.
Python Indentation Summary Points
- Indentation is not optional in Python — it is the syntax that defines block structure. Every block-opening statement ends with a colon, and every line inside the block is indented by a consistent number of spaces.
- PEP 8 specifies 4 spaces per indentation level. This is the universal convention across the Python ecosystem. Never use tab characters; configure your editor to expand Tab into 4 spaces.
- Nesting adds another 4 spaces at each level. The visual staircase this creates mirrors the logical nesting of your program. A block ends the moment a line returns to the previous indentation level — there is no closing keyword or brace.
- An
IndentationErrormeans a line's leading whitespace does not match any open indentation level. Read the error message, find the mismatched line, and correct its spacing to match the level it belongs to.
Indentation is one of those things that feels unfamiliar for a day or two and then becomes invisible. Once your editor is configured correctly and you have written a few dozen functions and loops, you will no longer think about it consciously — the structure just looks right when it is right and wrong when it is not.
Frequently Asked Questions
Python was designed with readability as a primary goal. Using indentation to define code blocks enforces a consistent visual structure and eliminates an entire category of bug where the indentation and the braces disagree about where a block ends.
The Python style guide (PEP 8) recommends 4 spaces per indentation level. Python itself only requires consistency — you can use 2, 3, or any number — but 4 is the standard used by virtually all Python code in the wild.
No. Python 3 raises a TabError if you mix tab characters and space characters within the same file's indentation. Always use one or the other — and the overwhelming convention is spaces.
An IndentationError is a syntax error Python raises when it finds a line whose indentation does not match what is expected. Common causes are a missing colon on a block header, a line that is indented too far or not far enough, and mixed tabs and spaces.
No. Python only interprets leading whitespace as indentation when it is at the start of a logical line of code. Inside a string literal, any whitespace is part of the string's value and has no effect on the block structure.
Python raises a SyntaxError — not an IndentationError — because the colon is required syntax for opening a block. The error message will point to the line missing the colon.
Each level of nesting adds another 4 spaces. A loop body inside a function is indented 8 spaces. An if block inside that loop is indented 12 spaces, and so on.
Yes. A block can contain a single statement. You can even place it on the same line as the header — for example, if x: print(x) — though PEP 8 recommends against this for anything but trivial one-liners.