Editor

IndentationError: unexpected indent

What it means

A line is indented more than Python expected. A deeper indent is only allowed right after a line that ends with a colon, such as an if, for or def line. Anywhere else, a line must start in the same column as the line before it.

1. An indented line that does not follow a colon

This raises the error

Broken
name = "Ada"
print("Hello,", name)
Output
Traceback (most recent call last):
  File "<exec>", line 2
    print("Hello,", name)
IndentationError: unexpected indent

The fix

Fixed
name = "Ada"
print("Hello,", name)
Output
Hello, Ada

The print is not inside any block, so it must start at the left edge, like the line above it.

Try fixing it yourself in the editor

2. One line indented deeper than the rest of its block

This raises the error

Broken
for n in [1, 2, 3]:
square = n * n
print(n, "squared is", square)
Output
Traceback (most recent call last):
  File "<exec>", line 3
    print(n, "squared is", square)
IndentationError: unexpected indent

The fix

Fixed
for n in [1, 2, 3]:
square = n * n
print(n, "squared is", square)
Output
1 squared is 1
2 squared is 4
3 squared is 9

Every line in a block must use the same indent. Both lines belong to the loop, so both get 4 spaces.

Try fixing it yourself in the editor

When you see this error, check

  • Compare the line Python points to with the line above it. They should start in the same column unless the line above ends with a colon.
  • Remove stray spaces at the start of pasted code.
  • Use the same indent for every line in a block, and 4 spaces per level.
  • If you meant the line to be inside a block, check that the if, for or def line above it is really there.

All Python errors · How to read a traceback · Step through your code