IndentationErrorWhat is an IndentationError?
Python uses indentation to know which lines belong to an if, a loop or a function. An IndentationError means the spaces at the start of a line do not fit.
What IndentationError means
IndentationError: expected an indented block after 'if' statement on line 2In Python, the spaces at the start of a line are part of the code. Every line inside an if, loop or function is indented by the same amount, usually 4 spaces. An IndentationError means a line's indent does not match any block Python can see.
The three messages you will meet:
- expected an indented block: a line ending in
:has nothing indented under it. - unexpected indent: a line is indented for no reason.
- unindent does not match any outer indentation level: a line was moved back, but not to a level that exists.
How to find it
Go to the line number and look at its left edge. Compare it with the line that opened the block (the one ending in :). Lines inside the block line up with each other, and the line after the block lines up with the opener. Mixing tabs and spaces can look right and still fail, so let your editor indent for you.
Run it: an empty if
Press Run and read the error from the bottom up.
lives = 0
if lives == 0:
print("Game over")
Go that is in the wrong place
Each player should get a Ready: line, then Go! should print once at the end. The program will not run. Fix the indentation.
for player in ["Ana", "Ben", "Cleo"]:
print("Ready:", player)
print("Go!")