Indentation refers to the spaces at the beginning of a line of code. In Python, indentation is used to define blocks of code and is mandatory.
Unlike many other programming languages, Python uses indentation instead of curly braces {}.
Basic Indentation
Example
if True:
print("Hello Python")
Output:
Hello Python
Indentation Inside Functions
Example
def greet():
print("Welcome")
print("Python")
greet()
Output:
Welcome
Python
Indentation Inside Loops
Example
for i in range(3):
print(i)
Output:
0
1
2
Missing Indentation Error
Python raises an error if indentation is missing.
Example
if True:
print("Hello")
Output:
IndentationError: expected an indented block
Using Multiple Statements in a Block
Example
age = 18
if age >= 18:
print("Eligible")
print("Can Vote")
Output:
Eligible
Can Vote
Nested Indentation
Example
age = 20
if age >= 18:
print("Adult")
if age >= 21:
print("Can Apply")
Output:
Adult
Indentation Using Spaces
Python recommends using 4 spaces for each indentation level.
Example
def show():
print("Python")
Tabs vs Spaces
You should use either tabs or spaces consistently throughout your code.
Incorrect Example
if True:
print("Hello")
print("Python")
Output:
TabError: inconsistent use of tabs and spaces
Summary
- Indentation defines code blocks in Python.
- Indentation is mandatory.
- Python typically uses 4 spaces for indentation.
- Missing indentation causes an
IndentationError. - Consistent indentation improves code readability.
- Avoid mixing tabs and spaces.
- Functions, loops, and conditions all require proper indentation.