What you'll learn
Quick Answer
Python uses indentation to define code blocks, so inconsistent spacing is a syntax error rather than a formatting preference. The three common messages are unexpected indent, meaning a line is indented with no reason to be, expected an indented block, meaning a colon was not followed by indented code, and TabError, meaning tabs and spaces are mixed. Configure your editor to insert four spaces for the Tab key and most of these disappear permanently.
Why Python Cares About Whitespace
Most languages mark blocks with braces and treat indentation as decoration. Python has no braces — the indentation is the structure.
// JavaScript: braces define the block, indentation is cosmetic
if (x > 0) {
console.log('positive');
}
# Python: the indentation IS the block
if x > 0:
print('positive')So an indentation mistake in Python is not untidy code — it changes what the program means, or stops it parsing at all.
The rules are short. A line ending in a colon must be followed by an indented block. Every line in a block must be indented by the same amount. And the amount is conventionally four spaces, though any consistent width works.
Because the error is about characters you cannot see, the fix is usually about making them visible. Turning on "render whitespace" in your editor is the single most useful thing you can do for this class of bug.
IndentationError: unexpected indent
This means a line is indented when nothing opened a block.
name = 'Riya'
print(name) # IndentationError: unexpected indentNothing before it ended with a colon, so there is no block for that line to belong to. The fix is to remove the extra indentation.
The same message appears when a block is inconsistently indented:
def greet():
print('hello')
print('again') # unexpected indent — deeper than its siblingsA more subtle version happens after pasting code from a website or a PDF, where the copied text carries leading spaces that are not obvious. If a line looks correctly aligned but still errors, delete the leading whitespace entirely and retype it.
The related message unindent does not match any outer indentation level means a line was dedented to a width that does not line up with any enclosing block:
def check(x):
if x > 0:
print('positive')
print('done') # 6 spaces — matches neither 4 nor 8
IndentationError: expected an indented block
This is the opposite: a colon opened a block and nothing was indented under it.
def greet():
print('hello') # IndentationError: expected an indented blockEvery construct ending in a colon needs indented code beneath it — def, class, if, elif, else, for, while, try, except, with.
It also appears when you leave a block empty as a placeholder:
def todo_later():
# nothing here — error
def todo_later():
pass # correct: pass is the explicit do-nothing statementpass exists precisely for this. Use it when sketching out functions or classes you have not written yet, or in an except block you genuinely want to be empty.
Note that a comment does not count as a block body. Python skips comments entirely, so a block containing only a comment still raises this error — you need pass as well.
TabError: The Invisible One
This is the most frustrating variant, because the code looks perfectly aligned.
TabError: inconsistent use of tabs and spaces in indentationA tab and four spaces can occupy the same visual width on screen while being completely different characters. Python 3 refuses to guess, and rejects a file that mixes them within the same block.
It happens most often when you copy code from a website that uses spaces into a file where you have been pressing Tab, or when two editors with different settings touch the same file.
The fixes, in order of usefulness:
- Configure your editor to insert spaces for Tab. In VS Code, click the "Spaces: 4" indicator in the status bar and choose Indent Using Spaces, then Convert Indentation to Spaces to fix the current file.
- Turn on whitespace rendering so tabs and spaces look different. In VS Code, set
"editor.renderWhitespace": "all". - Retype the indentation on the offending lines rather than trying to spot the difference.
PEP 8, Python's style guide, specifies four spaces, which is why nearly all Python code and every formatter follows it. Set it once in your editor and this error stops occurring.
The Indentation Bugs That Do Not Error
Worse than an IndentationError is indentation that parses fine and does the wrong thing. Python cannot warn you, because both versions are valid.
total = 0
for n in numbers:
total += n
print(total) # prints on every iteration
total = 0
for n in numbers:
total += n
print(total) # prints once, after the loopBoth run. Only one is usually what you meant.
The same trap with a return inside a loop:
def find_first_even(nums):
for n in nums:
if n % 2 == 0:
return n
return None # correct: after the whole loop
def broken(nums):
for n in nums:
if n % 2 == 0:
return n
return None # wrong: returns on the first iteration, alwaysAnd with try/except, where indenting too much code inside try catches exceptions you did not intend to catch, hiding real bugs.
The defence is habit rather than tooling: after writing a loop or a conditional, read the indentation deliberately and ask which lines run how often. An auto-formatter such as Black will make your file consistent, but it cannot know which behaviour you wanted.
