Free: 4 trials of 20 minutes, no cardStart free

Craftstack Academy
Python

Python IndentationError: unexpected indent, and how to fix it

· 10 min read

Your program is two lines long. You run it, and Python refuses to start:

Terminal
  File "main.py", line 2
    print("Hello,", name)
IndentationError: unexpected indent

IndentationError: unexpected indent means a line starts further to the right than Python expected. In Python, the spaces at the start of a line aren't decoration: they show which lines belong together. A line that is indented when nothing above it opened a new block confuses Python, so it stops before running anything. The fix is almost always to move that line back to the left. This article shows how to find the line, the five usual causes, and how to stop it from happening again.

Try it yourself

Save this as main.py and run python main.py:

main.py
name = input("Your name? ")
    print("Hello,", name)

You'll get the error above. Notice that Python didn't even ask for your name: indentation errors are found while Python reads the file, before any line runs.

What "unexpected indent" means

In Python, indentation (the spaces at the start of a line) creates blocks. A block always starts after a line that ends with a colon, like if, for, while, def or class:

python
if age >= 18:
    print("adult")      # inside the if: indented
print("done")           # back outside: not indented

Every line in the same block must start at the same position. The message says that Python found an indent it didn't expect: the line is further right, but the line above didn't end with a colon, so there's no new block for it to belong to.

Read the error in three parts:

  • File "main.py", line 2: the line that's indented by mistake.
  • The code line below it: Python prints the line so you can see it.
  • IndentationError: unexpected indent: the problem is the extra space at the start of that line.

Then ask: which block did I want this line to be in? Usually the answer is "the same one as the line above", and you move it left to match.

Cause 1: an accidental space or tab

The most common cause is the smallest: one stray space, often from pressing the space bar before typing, or from deleting a line above:

main.py
price = 4
 total = price * 3
print(total)
Terminal
  File "main.py", line 2
    total = price * 3
IndentationError: unexpected indent

One space is enough. Python doesn't care whether it's one space or eight: anything more than the line above, without a colon, is an unexpected indent. Delete the space so total starts in the same column as price.

A single tab at the very start of a file does the same:

Terminal
  File "main.py", line 1
    	x = 1
    ^
IndentationError: unexpected indent

The first line of a file must always start at the left edge.

Cause 2: code copied from a website, a chat or an AI answer

When you copy code from a tutorial, a forum or an AI chat, you often copy part of a larger block. The first line lands at the left edge where you pasted it, and the rest keeps its original indentation:

main.py
def greet(name):
    print("Hi", name)
        print("Welcome")
greet("Sam")
Terminal
  File "main.py", line 3
    print("Welcome")
IndentationError: unexpected indent

Line 3 is indented by eight spaces, but it's inside a function whose block uses four. Python sees eight and asks: which new block is this? There isn't one, so it stops.

The fix: select the pasted lines and adjust them to match the block they belong in. In VS Code and most editors, select the lines and press Shift+Tab to move them left, or Tab to move them right, four spaces at a time.

When you paste code from an AI assistant, check the indentation of the whole block before you run it, not only whether it "looks right". Our guide on learning to code with AI has more habits for working with pasted code.

Cause 3: a line meant to stay inside an if or a loop

Sometimes you want the line to be part of a block, but the line above it isn't the start of that block. Here, the programmer wanted the second print to run only when the score is high:

python
score = 72
print("Your score:", score)
    print("Well done")

This also gives unexpected indent, because print("Your score:", score) doesn't end with a colon. What's missing isn't spaces but an if:

python
score = 72
print("Your score:", score)
if score >= 70:
    print("Well done")

So before you delete the spaces, ask what you meant. If the line should run only sometimes, add the if, for or while that starts the block.

Cause 4: a line that wanders right after a block

After a block ends, the next line must go back to the indentation of the code before the block. If you go back only part of the way, you get a related error:

main.py
for n in range(3):
    print(n)
  print("done")
Terminal
  File "main.py", line 3
    print("done")
                 ^
IndentationError: unindent does not match any outer indentation level

The message is different: "unindent" means moving left. Line 3 moved left from four spaces to two, but no earlier block starts at two spaces, so Python can't tell where it belongs. Move it to the left edge (outside the loop) or to four spaces (inside the loop).

Cause 5: tabs and spaces mixed together

A tab and four spaces can look identical in your editor, but they aren't the same to Python. When one block mixes them, Python can't compare the indentation reliably:

Terminal
  File "main.py", line 3
    print("spaces")
TabError: inconsistent use of tabs and spaces in indentation

This one has its own name, TabError, but the cause is the same family. Most editors can fix it in one go:

  • VS Code: open the Command Palette (Ctrl+Shift+P or Cmd+Shift+P) and choose "Convert Indentation to Spaces".
  • Any editor: turn on "show whitespace" or "render whitespace" to see tabs as arrows and spaces as dots.

The official Python style guide, PEP 8, recommends four spaces per level. Set your editor to insert spaces when you press Tab, and the problem disappears.

The same error in your editor

Your editor often shows this problem with a red underline before you run anything, in its own words. One wording people search for is:

Editor
expected statement, found "indent" instead

Messages like this come from the editor's code checker, not from Python itself, and the exact words depend on the editor and its extensions. They point to the same line and the same fix.

What doesn't cause it

Two things look suspicious but are fine:

  • Indented comments. A line like # note is ignored by Python, wherever it starts.
  • Blank lines with spaces on them. Python ignores lines that contain only whitespace.

And indentation inside a string is part of the text, not code, so it never causes this error.

Errors that look alike

  • IndentationError: expected an indented block: the opposite problem. A line ends with a colon, but the next line isn't indented. See expected an indented block.
  • IndentationError: unindent does not match any outer indentation level: a line moved left, but not to a level that exists (cause 4).
  • TabError: inconsistent use of tabs and spaces in indentation: tabs and spaces mixed in one block (cause 5).
  • SyntaxError: invalid syntax on an else: if else is indented further than its if, Python 3.13 reports it as invalid syntax, not an indentation error:
Terminal
  File "main.py", line 4
    else:
    ^^^^
SyntaxError: invalid syntax

Line else: up with its if.

Wrong fixes that don't help

  • Deleting all indentation. It removes this error and creates expected an indented block errors for every if and def. Fix only the line Python names.
  • Adding spaces until it runs. Code that runs isn't always code that's right. A line moved into the wrong block will run at the wrong time, with no error at all.
  • Retyping the whole file. Show whitespace in your editor instead: you'll see the stray tab or space in seconds.

A debugging walkthrough

You pasted a function from a tutorial and Python reports unexpected indent on line 12. Here's the order to check:

  1. Go to line 12. Turn on "render whitespace" so you can see every space and tab.
  2. Look at the line above. Does it end with a colon? If not, line 12 shouldn't be further right than it.
  3. Decide which block line 12 belongs to. Inside the function? Then match the other lines in the function. Outside? Move it to the left edge.
  4. Select the whole pasted block and press Shift+Tab or Tab until its first line lines up correctly. The rest moves with it.
  5. Run again. If a new indentation error appears a few lines later, repeat: pasted code often has several.

Practice

Predict the error before you run each one.

  1. A file whose first line is print("start") (four spaces in front).
  2. for i in range(2):, then print(i), then print("again") (six spaces).
  3. if True:, then print("a"), then a line # just a note and print("b").

Answers. (1) unexpected indent on line 1: the first line must start at the left edge. (2) unexpected indent on line 3: six spaces, but the block uses four. (3) No error: it prints a and b, because the comment is ignored.

Frequently asked questions

How do I fix "unexpected indent" in Python?

Go to the line number in the message and move that line left until it lines up with the other lines in its block. If it should be in a new block, add the if, for or def line with a colon above it.

Why do I get unexpected indent when nothing looks wrong?

Usually there's an invisible tab or a single extra space. Turn on "render whitespace" in your editor, or delete the start of the line and indent it again with the Tab key.

How many spaces should I use in Python?

Four spaces per level is the standard from PEP 8. Python accepts any number, as long as every line in the same block uses the same amount.

Why does code from ChatGPT or a website give indentation errors?

When you paste part of a block, the first line loses its indentation and the rest keep theirs. Re-indent the pasted lines as one group with Tab or Shift+Tab.

Is IndentationError a SyntaxError?

Yes. IndentationError is a special kind of SyntaxError, which is why it appears before the program starts running.

A quick checklist

  1. Go to the line number in the message.
  2. Turn on visible whitespace in your editor.
  3. Compare with the line above: does it end with a colon?
  4. Move the line to match its block, or add the missing if, for or def.
  5. Use spaces only, four per level.

For a method that works on any error, read how to read an error message. The Python docs on indentation explain the exact rules Python follows.

1 beginner error a week

One common error, what it means and how to fix it, in a short email. Free, and you can unsubscribe in any email.

Python

Python NameError: name '...' is not defined (fix)

Fix Python's NameError: name is not defined: typos, a missing import, quotes, variables used before they exist or outside a function. With real output.

Error explained · · 11 min read

Python

Why does 0.1 + 0.2 not equal 0.3 in Python?

Why Python prints 0.30000000000000004 for 0.1 + 0.2, why 0.1 + 0.2 == 0.3 is False, and the three fixes: round for display, math.isclose() instead of ==, and Decimal for money. With code you can run.

Error explained · · 4 min read

Learn by writing the code yourself.

Twenty minutes with the tutor, right in your browser. No card, nothing to install.

Start the free trial
A session: the tutor's chat on the left, the code editor with a Java program and its output on the right