Python Arena
Step 3 of 5

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.")
Output
Score: 3
score = 3
print(f"Score: {score}")
if score > 5:
    print("You win!")
print("Game over.")
Output
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")
Python stops with
  File "main.py", line 3
    print("Access granted")
    ^^^^^
IndentationError: expected an indented block after 'if' statement on line 2

A line indented for no reason, with no colon before it:

print("Hello")
    print("World")
Python stops with
  File "main.py", line 2
    print("World")
IndentationError: unexpected indent

And lines of the same block indented by different amounts:

score = 8
if score > 5:
    print("You win!")
  print("Well played.")
Python stops with
  File "main.py", line 4
    print("Well played.")
                         ^
IndentationError: unindent does not match any outer indentation level

Line 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.

Your task

Challenge 1 of 3

The program stops with an IndentationError. Fix it, so that the right code grants access and Goodbye is printed every time. With the code 1234, the run looks like this:

Code: 1234
Access granted
Goodbye

Challenge 2

What does this program print? Type each line it prints.

Challenge 3

The restaurant's program offers free ice cream to everyone, but only kids under 13 should get it. Fix the indentation, so that the ice cream line belongs to the if. If the user types 8, the run looks like this:

Age: 8
Kids' menu available.
Free ice cream for kids!
Enjoy your meal.