Indentation and blocks
Python decides which lines belong to an if by their indentation: the spaces at the start of each line. All the lines of a block must be indented by the same amount, and four spaces is the standard. You rarely count the spaces yourself: the editor on this site starts the line after a colon already indented, and the Tab key adds four spaces to a line.
Indentation isn't just for looks. These two programs have the same lines, but the last line is indented differently:
score = 3
print(f"Score: {score}")
if score > 5:
print("You win!")
print("Game over.")
Score: 3score = 3
print(f"Score: {score}")
if score > 5:
print("You win!")
print("Game over.")
Score: 3
Game over.In the first program, print("Game over.") is part of the block, so it's skipped along with print("You win!"). In the second, it's back at the left edge, after the block, so it runs every time.
Indentation errors
When the indentation doesn't make sense, Python stops with an IndentationError before running anything. Here are the three you'll meet most often. A line after a colon that isn't indented leaves the if with an empty block:
code = input("Code: ")
if code == "1234":
print("Access granted")
File "main.py", line 3
print("Access granted")
^^^^^
IndentationError: expected an indented block after 'if' statement on line 2A line indented for no reason, with no colon before it:
print("Hello")
print("World")
File "main.py", line 2
print("World")
IndentationError: unexpected indentAnd lines of the same block indented by different amounts:
score = 8
if score > 5:
print("You win!")
print("Well played.")
File "main.py", line 4
print("Well played.")
^
IndentationError: unindent does not match any outer indentation levelLine 4 has two spaces: that's neither the block's four nor the left edge, so Python can't tell where the line belongs. Whatever the message, the fix is the same: look at the line it names and give it the indentation of the block it belongs to.