Indentation in Python
Indentation is the use of spaces or tabs at the beginning of a line to define the structure and grouping of code. In Python, indentation is not just for readability—it is a part of the syntax itself.
Unlike many programming languages that use braces {}
or keywords to mark blocks of code (like loops, functions, conditionals), Python uses indentation levels to group statements. This means that the amount of leading whitespace matters a lot.
Why is indentation important?
- It shows which statements belong together.
- It determines the scope or block of code (for example, what code runs inside an
if
statement or a for
loop).
- Incorrect indentation causes syntax errors.
Example of indentation in Python
if 5 > 2:
print("Five is greater than two!")
print("This line is also inside the if block")
print("This line is outside the if block")
Output:
Five is greater than two!
This line is also inside the if block
This line is outside the if block
- The two
print
statements that are indented belong to the if
block.
- The last
print
statement is outside the if
block because it’s not indented.
Incorrect indentation example — causes error
if 5 > 2:
print("This will cause an IndentationError")
Error:
IndentationError: expected an indented block
Indentation with loops
for i in range(3):
print(f"Iteration {i}")
print("Inside the loop")
print("Outside the loop")
Output:
Iteration 0
Inside the loop
Iteration 1
Inside the loop
Iteration 2
Inside the loop
Outside the loop
Mixing tabs and spaces
- Always use either spaces or tabs consistently (PEP 8 recommends 4 spaces per indentation level).
- Mixing tabs and spaces can cause errors or unpredictable behavior.
Summary:
- Indentation is mandatory in Python to define code blocks.
- Typical indentation is 4 spaces.
- Incorrect or inconsistent indentation raises
IndentationError
.
- Indentation improves code readability and structure.