IndentationError: unexpected indent — what it means and how to fix it

In Python, indentation isn’t decoration — it’s the structure. Spaces at the start of a line decide which block the line belongs to. “Unexpected indent” means a line is indented in a way that doesn’t line up with any block: almost always mixed tabs and spaces (which can look identical on screen), or a block pasted in at the wrong level.

The fix, in order

  1. Look at the line Python names, and the lines just above it. The reported line is where Python gave up; the mismatch usually starts a few lines earlier — an if, for, def or try without the body indented to match, or vice versa.
  2. Turn on visible whitespace in your editor (VS Code: View → Render Whitespace). Tabs show as arrows, spaces as dots — mixed lines become obvious immediately.
  3. Standardise on spaces. Select the whole file and convert indentation to spaces (VS Code: the spaces/tabs indicator in the bottom bar → “Convert Indentation to Spaces”), and set the editor to insert 4 spaces for the Tab key.
  4. Re-indent pasted code. Code copied from a web page or PDF often arrives with different spacing. Paste it, select the block, and use the editor’s indent/outdent (Tab / Shift+Tab) to level it as one piece.
  5. Check for a missing colon or an empty block above. A line after if x: that isn’t indented, or a block header with nothing under it, surfaces as an indentation error nearby — an empty block needs a pass line.

If it still happens

If the file looks perfectly aligned and still fails, suspect invisible characters from a copy-paste (non-breaking spaces from web pages are a known culprit). Retyping the offending lines by hand — not copying them again — clears what your eyes can’t see.

Common questions

Can I mix tabs and spaces if it looks aligned? No. Python 3 raises an error for inconsistent mixing, and even where it parses, a tab counts differently in different editors — the file that looks right can be structurally wrong. Pick spaces and let the editor enforce it.

Why does the error point at a line that looks fine? Python reports where it noticed the structure break, which is the first line that doesn’t fit — the actual mismatch (an earlier block at the wrong level) can be several lines above.

Related errors

TypeError: 'NoneType' object is not subscriptable · ModuleNotFoundError: No module named · ‘pip’ is not recognized