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 indent

Nothing 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 siblings

A 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 block

Every 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 statement

pass 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 indentation

A 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 loop

Both 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, always

And 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.

Frequently Asked Questions

Should I use tabs or spaces in Python? Spaces — four of them, as specified by PEP 8. Nearly all Python code and every formatter follows this. Set your editor to insert spaces when you press Tab and the whole category of TabError disappears.
Why does my code look aligned but still throw IndentationError? Almost certainly a mix of tabs and spaces, which can look identical on screen while being different characters. Turn on whitespace rendering in your editor, or convert the file's indentation to spaces.
What does expected an indented block mean? A line ended with a colon but nothing was indented beneath it. Every def, class, if, for, while, try and with needs an indented body. If you want it deliberately empty, use pass — a comment alone is not enough.
Can I use two spaces instead of four? Python only requires consistency within a block, so two spaces will run. But four is the convention, formatters assume it, and mixing widths across a project causes avoidable friction.
Why did my code break after pasting from a website? Copied text often carries different indentation characters, or leading whitespace that is not visible. Delete the indentation on the pasted lines and retype it, and set your editor to convert indentation to spaces.