indentation
In programming, indentation refers to using spaces or tabs at the beginning of a line of code to visually separate and group code blocks.
In Python, indentation is a fundamental syntax aspect because the language relies on indentation levels to define code blocks. There’s no such thing as curly braces {}
or begin
and end
delimiters for code blocks in Python. Therefore, indentation is not only a practice for improving code readability. It’s also a syntactical requirement that became a tool for achieving code readability.
You must consistently indent code blocks, such as the body of a function, loop, or conditional statement because indentation defines the logical structure of your code.
Use spaces instead of tabs to indent your Python code. Additionally, you must use the same number of spaces —typically four— for each indented code block.
Mixing tabs and spaces can lead to errors, as the Python interpreter strictly enforces indentation levels. If your code isn’t indented properly, you may encounter IndentationError
or TabError
, which will prevent your program from running.
Example
Here’s an example demonstrating indentation in a Python function:
>>> def greet(name=None):
... if name:
... print(f"Hello, {name}!")
... else:
... print(f"Hello, Pythonista!")
...
>>> greet("Alice")
Hello, Alice!
>>> greet()
Hello, Pythonista!
In this example, the if
and else
statements form a block indented by four spaces inside the greet()
function. The calls to print()
are further indented, which makes them the body of their respective if
and else
clauses.
Related Resources
Tutorial
Invalid Syntax in Python: Common Reasons for SyntaxError
In this step-by-step tutorial, you'll see common examples of invalid syntax in Python and learn how to resolve the issue. If you've ever received a SyntaxError when trying to run your Python code, then this is the guide for you!
For additional information on related topics, take a look at the following resources:
By Leodanis Pozo Ramos • Updated May 21, 2025