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 afor
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 theif
block. - The last
print
statement is outside theif
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.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.