All Python errors
IndentationError in Python: unexpected indent
Unexpected indent means a line begins further to the right than Python expects: nothing above it opens a block. To fix it, remove the extra spaces so the line starts level with its neighbours.
Code with the error
total = 0
for step in range(4):
total += step
print(total)
Error message (Python 3.12, last line)
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: LoopsFrequently 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.