Python - Indentation
What is Indentation?
In Python, indentation refers to the whitespace at the beginning of a line. Unlike many programming languages that use curly braces {} to define code blocks, Python uses indentation to represent blocks of code.
Why is Indentation Important?
- It defines the **structure** and **scope** of code.
- Python throws an
IndentationErrorif indentation is not correct. - Makes code more readable and clean.
How to Use Indentation?
Use 4 spaces (recommended by PEP 8) or a tab. Be consistent across your file.
python
def greet(): print("Hello, World!") # This line is indented by 4 spaces greet()
When Does Indentation Matter?
- In function definitions
- In loops (
for,while) - In conditionals (
if,else,elif) - In classes
- Any place where a block of code is expected
Correct vs Incorrect Indentation
Correct
for i in range(3): print("Count:", i)
Incorrect
for i in range(3): print("Count:", i)# IndentationError!
Pros and Cons
Pros
- Enforces clean and readable code
- No need for curly braces
- Structure is visually clear
Cons
- Whitespace errors are harder to spot
- Mixing tabs and spaces causes bugs
- Not beginner-friendly at first
Best Practices
- Use 4 spaces per indentation level (PEP 8)
- Don’t mix tabs and spaces
- Use linters (e.g., Flake8) or IDE support