Python does not use curly braces or begin/end keywords to mark code blocks. Instead, it relies on whitespace — specifically indentation — to define structure. That makes whitespace one of the very first things a beginner needs to understand, because getting it wrong causes errors before any logic runs.
In languages like JavaScript, C, or Java, you can write an entire program on one line (within limits) and it will still run. Python won't allow that for code blocks. The column position of each line carries meaning. This tutorial covers every whitespace rule you need to write clean, working Python code from day one.
What Whitespace Means in Python
Whitespace is any character that takes up space without being a visible glyph. In Python, the three whitespace characters that matter are the space (U+0020), the tab (U+0009), and the newline (U+000A). The Python parser reads these characters and uses them to determine where one statement ends and another begins, and which lines belong inside a block.
When Python encounters a colon (:) at the end of a statement — such as after if, for, while, def, or class — it expects the next non-blank line to be indented further than the statement that introduced the colon. Every line at the same indentation level belongs to the same block.
Python 3 treats indentation as part of the language grammar, not just a formatting convention. A line that is indented at the wrong level produces a SyntaxError or IndentationError before Python even tries to execute the code.
The example below shows a function with a correctly indented body and a nested if block inside a loop. Notice how each additional level of structure adds another layer of indentation.
def check_scores(scores): # top level — 0 spaces
for score in scores: # function body — 4 spaces
if score >= 90: # loop body — 8 spaces
print("pass") # if body — 12 spaces
else: # back to 8 spaces
print("review needed") # else body — 12 spaces
Each level is four spaces deeper than the one containing it. When Python reads a line that returns to a lower indentation level, it knows the block has ended. There is no closing brace or keyword required.
"Readability counts." — Tim Peters, The Zen of Python (PEP 20)
Indentation Rules Every Beginner Must Know
The single most important rule is consistency. Python does not mandate exactly four spaces — it mandates that every line in a block uses the same indentation as the other lines in that block. In practice, four spaces is the universal standard, recommended by PEP 8 and used by virtually every major Python project.
Spaces vs. tabs
Python 3 does not allow you to mix spaces and tabs for indentation within the same source file. If one line uses a tab and the next uses spaces, Python raises a TabError. Configure your editor to insert four spaces when you press the Tab key. This is the default behavior in VS Code, PyCharm, and most modern editors when working with Python files.
Never mix tabs and spaces. Even if a mixed file appears visually aligned in your editor, Python's parser counts column positions differently than your editor renders them, and the result is a TabError at runtime.
The following table summarizes the common indentation mistakes and what error each one produces.
- Error
- IndentationError: expected an indented block
- Example
if True:followed by an unindented line
- Error
- IndentationError: unindent does not match any outer indentation level
- Example
- First line of a block uses 4 spaces, second line uses 5
- Error
- TabError: inconsistent use of tabs and spaces in indentation
- Fix
- Run
python -m tabnanny yourfile.pyto detect mixed indentation
- Error
- IndentationError: unexpected indent
- Example
- A line indented with no preceding colon to open a block
Build a correctly indented Python if statement. Click each token in the right order to form: if x > 0: then a properly indented print(x) on the next line. Note: the newline + spaces token represents pressing Enter and indenting.
Nested Indentation
When you write a block inside another block — such as an if statement inside a for loop — you add another four spaces on top of the existing indentation. Python tracks each level separately. The outer block stays at its level and the inner block goes one level deeper.
for i in range(3): # level 0 — 0 spaces
if i == 1: # level 1 — 4 spaces
print("found one") # level 2 — 8 spaces
print(i) # level 1 again — 4 spaces
If you are unsure whether a line belongs to the right block, read the indentation level out loud: "zero spaces, four spaces, eight spaces." Whenever you return to a lower level, the block at the higher level has closed. This mental model works for any depth of nesting.
This function should print "warm" when the temperature is above 25. One line has an indentation error. Click the line you think is wrong, then hit check.
print("cool") is the body of the else block, so it needs to be indented one level deeper than else:. As written, Python sees it as a separate statement outside the if/else, which causes an IndentationError.
Blank Lines and Spacing Around Operators
Indentation is not the only whitespace that matters in Python. Blank lines and the spaces you put around operators also affect how readable and maintainable your code is. PEP 8 — the official Python style guide — provides specific rules for both.
Blank lines between definitions
Place two blank lines before and after each top-level function or class definition. Inside a class, separate each method with one blank line. Inside a function body, use blank lines sparingly to separate logical steps — there is no rule against them, but multiple consecutive blank lines inside a function are a style warning.
def add(a, b):
return a + b
# <-- two blank lines
#
def multiply(a, b):
return a * b
# <-- two blank lines
#
class Calculator:
def __init__(self):
self.history = []
# <-- one blank line between methods
def run(self, a, b):
result = add(a, b)
self.history.append(result)
return result
Spaces around operators
PEP 8 specifies that binary operators — assignment, arithmetic, comparison, and Boolean — should have one space on each side. The goal is to make expressions readable at a glance rather than requiring the reader to parse dense character sequences.
# Correct spacing
x = 10
result = x + 5
if result == 15:
print("correct")
# Incorrect — no spaces around operators
x=10
result=x+5
The exception is keyword arguments in function calls and default parameter values in function definitions, where PEP 8 says to omit the spaces around the =.
# Keyword arguments — no spaces around =
print("hello", end="\n")
# Default parameter — no spaces around =
def greet(name="world"):
print(f"Hello, {name}")
Whitespace inside parentheses and brackets
PEP 8 says to avoid spaces immediately inside parentheses, brackets, and braces. The content of a call or a literal collection should follow the opening delimiter directly, with no leading space.
# Correct
scores = [90, 85, 72]
print(scores[0])
# Incorrect — extra spaces inside brackets
scores = [ 90, 85, 72 ]
print( scores[ 0 ] )
Inside parentheses, Python also ignores newlines. This lets you split a long function call or list across multiple lines without a backslash, which is the preferred way to handle lines that would otherwise exceed 79 characters.
# Multi-line call using implicit line continuation
result = some_function(
argument_one,
argument_two,
argument_three,
)
How to Use Whitespace Correctly in Python
Follow these four steps whenever you write a new Python file. They cover the rules that matter most for avoiding errors and producing readable code.
-
Indent every code block with 4 spaces
After a colon at the end of an
if,for,while,def, orclassstatement, press Tab (configured to insert 4 spaces in your editor) to begin the indented block. Every line belonging to that block must share the same indentation level. Return to the original indentation level to close the block. -
Keep indentation consistent within each block
All lines in the same block must use the exact same number of spaces. If the first line uses 4 spaces, every other line in that block must also use 4 spaces. Python compares column positions, not just whether a line is indented at all. A single extra space triggers an
IndentationError. -
Add blank lines to separate logical sections
Place two blank lines before and after top-level function and class definitions. Inside a class, separate each method with one blank line. Inside a function body, use a single blank line to separate logically distinct steps. Avoid multiple consecutive blank lines inside function bodies.
-
Space operators and commas correctly
Surround binary operators (
=,+,-,*,/,==,!=,and,or) with a single space on each side. After commas in function arguments and list items, place a single space. Omit spaces around=in keyword arguments and default parameter values. Do not add spaces immediately inside parentheses or brackets.
Python Whitespace Summary Points
- Python uses indentation as syntax: every code block must be indented one consistent level deeper than the statement that introduced it. Four spaces per level is the PEP 8 standard.
- Mixing tabs and spaces in Python 3 raises a
TabError. Configure your editor to use spaces only, and always use the same number of spaces per level throughout a file. - Blank lines help humans understand structure. Two blank lines between top-level definitions and one blank line between class methods are the PEP 8 conventions. Inside functions, use blank lines to separate logically distinct steps.
- Spaces around binary operators make expressions readable. Omit spaces around
=only in keyword arguments and default parameter values. Do not add spaces immediately inside parentheses, brackets, or braces.
Whitespace rules in Python are not arbitrary. They enforce a visual structure that makes it impossible for the indentation to lie about how code is grouped. Once you internalize the four-space rule and the blank-line conventions, reading and writing Python code becomes significantly faster — and your IndentationError count drops to zero.
Frequently Asked Questions
Whitespace in Python refers to any character that creates space without being visible text, including spaces, tabs, and newlines. Python uses whitespace — particularly indentation — as part of its syntax to define code blocks such as loops, conditionals, and function bodies.
PEP 8, Python's official style guide, recommends 4 spaces per indentation level. While Python accepts any consistent number of spaces (or tabs), mixing tabs and spaces in the same block causes a TabError. Using 4 spaces is the standard used across virtually all professional Python code.
No. Python 3 raises a TabError if you mix tabs and spaces for indentation within the same block. Python 2 allowed this but produced unpredictable behavior. Always use one or the other — 4 spaces is the strongly recommended choice.
An IndentationError occurs when Python finds a line of code that does not match the expected indentation level. Common causes include forgetting to indent the body of an if statement, loop, or function, accidentally using the wrong number of spaces, or inconsistently indenting lines within the same block.
Inside parentheses, brackets, and braces, Python ignores newlines and treats the content as one logical line. This allows you to split long function calls or lists across multiple lines without using a backslash continuation character. PEP 8 advises avoiding extra spaces immediately inside parentheses.
PEP 8 recommends two blank lines between top-level function and class definitions, and one blank line between methods inside a class. Blank lines within a function body should be used sparingly to separate logically distinct steps.
Python does not raise errors for trailing whitespace at the end of a line, but PEP 8 explicitly says to avoid it. Trailing whitespace causes problems with version control diff tools, makes code harder to review, and is flagged by linters such as flake8.