Code with the error

total = 0
    for step in range(4):
        total += step
print(total)

Error message (Python 3.12, last line)

IndentationError: unexpected indent

Corrected code

total = 0
for step in range(4):
    total += step
print(total)

Output

6

Common causes

  • A stray space or Tab at the start of a line.
  • Code was pasted from a page or a chat together with its indentation.
  • The if or for line above was deleted but its block stayed shifted.
  • A single line inside a block is shifted further than the others.

Practise in the course

Lesson: Loops

Frequently asked questions

When is an indent expected?

Only after a line that ends with a colon, or inside open brackets.

How is it different from “expected an indented block”?

That message means the indent is missing; unexpected indent means there is one where none should be.