How to Fix Python IndentationError โ Complete Guide
How to Fix Python IndentationError โ Complete Guide ๐
Python ka sabse unique error โ IndentationError. Doosri languages mein nahi hota! Spaces vs Tabs, wrong alignment, missing indentation โ beginners ka nightmare. Complete fix guide with examples. Data Insights par.
โก Quick Answer
IndentationError tab aata hai jab Python code mein indentation (spacing/alignment) galat ho โ kyunki Python spaces/tabs se code blocks define karta hai (curly braces {} ki jagah). Missing indent, extra indent, ya tabs aur spaces mix karna โ sab IndentationError dega. Quick Fix: 4 spaces per indent level use karo, tabs avoid karo, aur IDE ka "Show Whitespace" ON karo.
Error Type: Syntax Error (Compile Time โ code chalta hi nahi)
Language: Python (UNIQUE โ only Python has this!)
Difficulty: Easy to Fix (but tricky to find sometimes)
Frequency: โญโญโญโญโญ Extremely Common for Beginners
๐ฅ Error Message
IndentationError ke 4 common messages โ har ek alag situation mein aata hai:
๐ Common IndentationError Messages:
Message 1 โ Expected indent missing: IndentationError: expected an indented block after 'if' statement on line 1
Message 2 โ Unexpected indent:
IndentationError: unexpected indent
Message 3 โ Unindent does not match:
IndentationError: unindent does not match any outer indentation level
Message 4 โ Tabs and spaces mixed:
TabError: inconsistent use of tabs and spaces in indentation
๐ก Important: IndentationError actually SyntaxError ka subclass hai. TabError IndentationError ka subclass hai. Yeh compile-time error hai โ code execute hi nahi hoga jab tak fix nahi karo. Doosre errors (TypeError, NameError) runtime mein aate hain โ yeh toh code run hone se pehle hi crash hota hai.
๐ Definition
IndentationError is a syntax error in Python raised when the code's indentation (whitespace at the beginning of lines) is incorrect. Python uses indentation (spaces or tabs) to define code blocks โ unlike other languages that use curly braces {}. Every code block (after if, else, for, while, def, class, try, with) MUST be indented consistently. IndentationError means Python cannot understand which lines belong to which block because the spacing is wrong.
โข C/Java:
if(x) { code; } โ curly braces define blocks. Indentation optional (just for readability).โข Python:
if x: + INDENTATION defines blocks. No curly braces โ indentation IS the syntax!โข This is why IndentationError is unique to Python โ other languages don't have it.
๐ฏ Hinglish Explanation
Simple Words Mein: Python mein code LIKHNE ka tarika alag hai โ har block ke andar ka code LEFT side se THODA ANDAR hona chahiye. Jaise kitaab mein paragraphs start mein thode andar se shuru hote hain โ waise Python mein if, for, def ke andar ka code 4 spaces andar hota hai. Agar yeh spacing galat hai โ IndentationError!
Real Life Example: Socho ek office report mein headings aur sub-points hain:
Sales Report: Total Sales: โน10 Lakh โ 4 spaces indent (sub-point) Top Product: Laptop โ Same level (same indent) Breakdown: North: โน3 Lakh โ 8 spaces indent (sub-sub-point) South: โน2 Lakh โ Same level (same indent)
Yahi Python mein hota hai:
if condition:
code line 1 โ 4 spaces indent (belongs to if)
code line 2 โ Same level (belongs to if)
if nested:
nested code โ 8 spaces indent (belongs to inner if)
code outside โ No indent (not part of if)
4 Rules Yaad Rakho:
(1) Colon (:) ke baad HAMESHA indent karo โ if, for, def, class ke baad.
(2) Same block ke saare lines SAME level par hone chahiye โ 4 spaces ya 8 spaces, mix nahi.
(3) Tabs aur spaces KABHI mix mat karo โ ek choose karo (4 spaces recommended).
(4) Block khatam hone ke baad indent WAPAS laao โ back to original level.
๐ค Why This Error Happens?
๐ 5 Common Root Causes:
| # | Reason | Error Type |
|---|---|---|
| 1 | Indent missing after colon (:) | expected an indented block |
| 2 | Extra/unnecessary indent | unexpected indent |
| 3 | Inconsistent indent level in same block | unindent does not match |
| 4 | Tabs aur Spaces mix karna | TabError (inconsistent use) |
| 5 | Code copy-paste karte waqt indent break | Various indent errors |
๐ป Real Examples
โ Example 1: Expected Indent Missing After Colon
# if ke baad indent nahi kiya if age > 18:
print("Adult") # IndentationError! โ indent missingโ Example 2: Unexpected Indent
# Top-level code ko indent nahi karna chahiye name = "Jatin" print(name) # IndentationError! โ unnecessary indentโ Example 3: Inconsistent Indent Level
# Same block mein different indent levels if age > 18:
print("Adult") # 4 spaces โ
print("Can vote") # 6 spaces โ โ IndentationError!โ Example 4: Tabs and Spaces Mixed
# Tab aur Space dikhte same hain but Python mein alag! if x > 0:
print("Positive") # This line uses SPACES print("Number") # This line uses TAB โ TabError!โ Example 5: Function/Class Body Missing
# Function body completely missing def calculate(): # No code inside function โ IndentationError!
x = 10
print(x)
๐ Output โ Actual Error You'll See
Example 1 Output (Missing Indent):
File "example.py", line 3 print("Adult") ^ IndentationError: expected an indented block after 'if' statement on line 1Example 2 Output (Unexpected Indent):
File "example.py", line 2 print(name) ^ IndentationError: unexpected indentExample 3 Output (Unindent Mismatch):
File "example.py", line 3 print("Can vote") ^ IndentationError: unindent does not match any outer indentation levelExample 4 Output (Tab + Space Mix):
File "example.py", line 3 print("Number") ^ TabError: inconsistent use of tabs and spaces in indentationExample 5 Output (Empty Body):
File "example.py", line 4 x = 10 ^ IndentationError: expected an indented block after function definition on line 1๐ง How to Fix
โ Fix 1: Add Proper Indent After Colon
# 4 spaces indent after every colon (:) if age > 18: print("Adult") # 4 spaces โ
print("Can vote") # Same 4 spaces โ
for i in range(5):
print(i) # 4 spaces โ
def greet(name):
return f"Hello {name}" # 4 spaces โ
โ Fix 2: Remove Unexpected Indent
# Top-level code โ NO indent name = "Jatin" # No indent โ
print(name) # No indent โ
# Only indent INSIDE blocks
if name == "Jatin":
print("Found!") # Indent HERE โ
print("Done") # No indent โ outside if block โ
โ Fix 3: Make Indent Levels Consistent
# Same block = SAME indent level (4 spaces each) if age > 18: print("Adult") # 4 spaces โ
print("Can vote") # 4 spaces โ
(same level) print("Can drive") # 4 spaces โ
(same level)
# Nested blocks = add 4 more spaces each level
for i in range(5):
if i % 2 == 0:
print(f"{i} is even") # 8 spaces (4+4) โ
else:
print(f"{i} is odd") # 8 spaces (4+4) โ
โ Fix 4: Convert Tabs to Spaces
# VS Code mein Tabs โ Spaces convert karo: # 1. Ctrl+Shift+P (Command Palette) # 2. Type: "Convert Indentation to Spaces" # 3. Select โ done!
# Settings mein permanently fix karo:
# VS Code โ Settings โ "Insert Spaces" โ Check
ON
# VS Code โ Settings โ "Tab Size" โ 4
# Ab Tab key press karne par 4 spaces
insert honge
# Python command line se fix karo:
# python -m tabnanny example.py โ Check for tab issues
# autopep8 --in-place example.py โ Auto-fix indentation
โ Fix 5: Empty Block โ Use pass
# Function body khali chahiye? โ Use pass def calculate(): pass # Placeholder โ no error โ
class Employee:
pass # Empty class โ will add methods later โ
if x > 10:
pass # TODO: implement later โ
else:
print("Not greater")
โ ๏ธ Common Mistakes
Mistake 1: Tabs Aur Spaces Mix Karna
Sabse DANGEROUS aur sabse hard-to-find issue. Tab aur Space dikhte same hain screen par โ but Python mein alag treat hote hain. Notepad mein code likha (tabs), VS Code mein paste kiya (spaces mix ho gaye) โ TabError! Solution: IDE mein "Show Whitespace" ON karo โ tabs arrow (โ) dikhte hain, spaces dots (ยท) dikhte hain.
Mistake 2: Code Copy-Paste Se Indent Break
Stack Overflow, tutorial, ya blog se code copy karte waqt indentation break ho jaati hai. Browser se paste karne par tabs/spaces gadbad ho sakte hain. Solution: Paste ke baad ALWAYS indent re-check karo. VS Code mein Select All + Format Document (Shift+Alt+F) karo.
Mistake 3: Colon (:) Ke Baad Indent Bhoolna
Beginners if, for, def likhte hain but indent karna bhool jaate hain. Rule: Jab bhi colon (:) likho โ agle line ko indent karo! Python mein colon = "aage ka code is block ka part hai, indent karo."
Mistake 4: 2 Spaces vs 4 Spaces Inconsistency
Kuch lines 2 spaces indent, kuch 4 spaces โ IndentationError! PEP 8 standard: 4 SPACES. Project mein consistent rakho โ agar 4 choose kiya toh poore project mein 4. IDE settings mein fix karo permanently.
Mistake 5: else/elif Ka Indent if Se Match Na Karna
if ka indent kuch aur, else ka kuch aur โ "unindent does not match." if, elif, else SAME level par hone chahiye. Aur unke body mein SAME indent hona chahiye.
๐ฌ Interview Questions
Q1: Python mein IndentationError kyun unique hai?
Ans: IndentationError sirf Python mein hota hai kyunki Python indentation se code blocks define karta hai โ curly braces {} use nahi karta (jaise C, Java, JavaScript mein). Python mein whitespace (spaces/tabs) SYNTAX ka part hai โ sirf readability ke liye nahi. Agar indent galat hai, Python samajh hi nahi paata kaunsa code kaunse block ka part hai. Isliye indent error = syntax error. Other languages mein indent galat ho toh code ugly dikhta hai but CHALTA hai. Python mein nahi chalega โ error aayega!
Q2: Tabs vs Spaces โ kya use karna chahiye Python mein?
Ans: SPACES โ always! PEP 8 (Python's official style guide) clearly recommends 4 spaces per indent level. Tabs technically legal hain lekin spaces ke saath mix karna TabError deta hai. Python 3 mein tabs aur spaces mix karna explicitly banned hai โ TabError raise hota hai. VS Code, PyCharm sab mein Tab key ko "Insert 4 Spaces" mein configure kar sakte ho โ Tab key press karo, 4 spaces insert honge. Community standard hai 4 spaces โ saare major Python projects (Django, Flask, Pandas) yehi follow karte hain.
Q3: IndentationError aur SyntaxError mein kya relationship hai?
Ans: IndentationError SyntaxError ka SUBCLASS hai โ inheritance hierarchy: Exception โ SyntaxError โ IndentationError โ TabError. Matlab: (1) IndentationError ek special type ki SyntaxError hai โ specifically indentation se related. (2) except SyntaxError: se IndentationError bhi catch ho jayega (parent class se). (3) TabError IndentationError ka aur specific version hai โ specifically tabs/spaces mixing ke liye. Dono compile-time errors hain โ code execute hone se pehle hi fail ho jaate hain. TypeError, ValueError jaisi runtime errors se alag โ woh code execution ke dauran aate hain.
๐ Related Errors
| Related Error | When It Happens | Difference from IndentationError |
|---|---|---|
| TabError | Tabs + Spaces mix | IndentationError ka subclass โ specifically tab mixing |
| SyntaxError | Wrong code grammar/structure | Parent class โ broader syntax issues (missing colon, bracket) |
| NameError | Variable not defined | Runtime error โ IndentationError is compile-time |
| TypeError | Wrong data type in operation | Runtime error โ unrelated to whitespace |
๐ก Hierarchy: Exception โ SyntaxError โ IndentationError โ TabError. Catch karne ke liye specific se general โ except TabError most specific, except SyntaxError catches all three.
๐ Summary
๐ฏ What Is IndentationError?
Python-specific syntax error jab code ka whitespace (indentation) galat ho. Python uses indentation as syntax โ unlike other languages that use {}. Compile-time error โ code run hi nahi hoga.
๐ฏ Top 5 Common Causes:
1. Indent missing after colon (:) โ if, for, def, class
2. Extra/unexpected indent on regular code
3. Inconsistent indent levels in same block (4 vs 6 spaces)
4. Tabs and spaces mixed together
5. Empty function/class body without pass
๐ฏ 4 Golden Rules:
1. 4 SPACES per indent level โ PEP 8 standard (never tabs)
2. Colon ke baad ALWAYS indent โ if, for, def, class, try, with
3. Same block = Same indent โ har line same level par
4. IDE settings fix karo โ Tab = 4 Spaces, Show Whitespace ON
๐ฏ Key Takeaway:
IndentationError fix karna easy hai โ lekin dhundhna kabhi kabhi mushkil. Tabs aur Spaces dikhte same hain but Python mein alag hain. IDE mein "Render Whitespace" ON karo. Code paste karne ke baad reformat karo. VS Code mein Shift+Alt+F (Format Document) โ instant fix. PEP 8 follow karo โ 4 spaces, consistent levels, no tabs.
๐ฏ IndentationError โ Complete Guide Done!
Ab tum Python IndentationError ko easily identify aur fix kar sakte ho. 5 real scenarios, 5 fix methods, aur 5 common mistakes โ sab kuch cover ho gaya. Yaad rakho โ 4 spaces always, tabs never, IDE settings fix karo, aur colon ke baad indent karo. Python Errors Covered So Far: TypeError, ValueError, NameError, IndexError, KeyError, IndentationError โ 6 errors done! Data Insights Debugging Guide series continue ho rahi hai. Data Insights par sab FREE, detailed, Hinglish mein.
Happy Debugging & Keep Coding! ๐
๐ฌ Comments (0)
Loading comments...