IndentationError: unexpected indent
IndentationError: unexpected indent in Python means a line starts further to the right than Python expected. Python only allows a line to be indented more than the one above it right after a line that ends with a colon.
How do I fix IndentationError: unexpected indent?
IndentationError: unexpected indent means a line starts further right than Python allows. A line may only be indented more than the one above it if that line ends with a colon, like if, for or def. Move the line left so it starts in the same column as the line above. Your program does not run until this is fixed.
- 1. Go to the reported lineCompare its left edge with the line above it. Even one extra space at the start causes this error.
- 2. Look for a colon aboveIf the line above does not end with a colon, both lines must start in exactly the same column.
- 3. Fix pasted codeSelect the pasted block and press Shift+Tab until its first line touches the left edge, then re-indent the body.
What does IndentationError: unexpected indent mean?
Python uses the spaces at the start of a line to group code into blocks. A new, deeper block can only start after a line ending in a colon, such as if, for, def or while. If a line is pushed right anywhere else, even by one space, Python stops before running anything and points at that line.
Why does IndentationError: unexpected indent happen?
1. A stray space at the start of a line
One extra space is enough. It is easy to miss on a phone keyboard.
Breaks
name = "Ada"
print(name)Works
name = "Ada"
print(name)2. Indenting after a line with no colon
Only lines ending in : open a new block. A normal statement cannot have an indented body.
Breaks
total = 0
total = total + 5Works
total = 0
total = total + 53. Code pasted from a website or chat
Copied code often keeps the indentation of the page it came from, so the first line sits too far right.
Breaks
for n in range(3):
print(n)Works
for n in range(3):
print(n)How to find it in your own code
Checklist: 1) Go to the line number in the message. 2) Compare its left edge with the line above. 3) If the line above does not end with a colon, the two lines should start at the same place. 4) Select the whole pasted block and remove indentation (Shift+Tab in most editors) until the top line touches the left edge.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.