IndentationError in Python: Causes and Fixes with Simple Examples
What is IndentationError in Python?
An IndentationError in Python occurs when the spacing (indentation) of your code is incorrect.
In simple words, Python is saying:
“Your code blocks are not aligned properly.”
Unlike many languages, Python uses indentation to define code blocks, so correct spacing is mandatory.
Common IndentationError Messages
IndentationError: expected an indented block
IndentationError: unexpected indent
Why Indentation Is Important in Python
Python uses indentation to understand:
-
Loops
-
Conditions
-
Functions
-
Classes
Incorrect indentation breaks program structure and causes errors.
Example 1: Missing Indentation
❌ Incorrect Code
if True:
print("Hello Python")
❌ Error
IndentationError: expected an indented block
✔ Correct Code
if True:
print("Hello Python")
Example 2: Unexpected Indentation
❌ Incorrect Code
print("Start")
print("Hello")
❌ Error
IndentationError: unexpected indent
✔ Correct Code
print("Start")
print("Hello")
Example 3: Mixing Tabs and Spaces
❌ Incorrect Code
if True:
print("Python")
print("Error")
❌ Error
TabError: inconsistent use of tabs and spaces in indentation
✔ Correct Code
if True:
print("Python")
print("Error")
✔ Use spaces only (recommended: 4 spaces)
Example 4: Indentation Error in Functions
❌ Incorrect Code
def greet():
print("Hello")
❌ Error
IndentationError
✔ Correct Code
def greet():
print("Hello")
Example 5: Indentation Error in Loops
❌ Incorrect Code
for i in range(3):
print(i)
❌ Error
IndentationError
✔ Correct Code
for i in range(3):
print(i)
Example 6: Indentation Error After try–except
❌ Incorrect Code
try:
print(10 / 2)
except:
print("Error")
❌ Error
IndentationError
✔ Correct Code
try:
print(10 / 2)
except:
print("Error")
How to Fix IndentationError Easily
✔ Use 4 spaces for indentation
✔ Avoid mixing tabs and spaces
✔ Use a code editor with auto-indent
✔ Enable “show whitespace”
✔ Format code properly
Best Editors to Avoid Indentation Errors
-
VS Code
-
PyCharm
-
Sublime Text
-
Thonny (great for beginners)
IndentationError vs SyntaxError
| Error | Meaning |
|---|---|
| SyntaxError | Invalid code structure |
| IndentationError | Incorrect spacing |
✔ IndentationError is a type of SyntaxError
Summary
An IndentationError occurs when Python code blocks are not properly aligned.
Once you follow consistent indentation rules, this error becomes easy to avoid.
❓ Frequently Asked Questions (FAQ)
Q1: Is IndentationError common?
Yes, very common for beginners.
Q2: Can try–except catch IndentationError?
No, it occurs before execution.
Q3: How many spaces should I use?
4 spaces (Python standard).
📌 Final Tip
Never use tabs + spaces together - always use spaces.
Comments
Post a Comment