Blocks of Code

A block can have as many lines as you need. All the indented lines under the if belong to its block, and when the condition is true, they all run, one after another:

temperature = 32
if temperature > 30:
    print("It's very hot")
    print("Drink plenty of water")
print("Have a nice day")

This prints:

It's very hot
Drink plenty of water
Have a nice day

The block ends at the first line that isn't indented. That line, print("Have a nice day"), is outside the block, so it runs every time, whether the condition is true or false.

That's why indentation matters so much in Python. A typical mistake is to forget to indent a line that belongs to the block. Python doesn't report an error, because the program is still correct Python. It just does something different from what you meant:

temperature = 20
if temperature > 30:
    print("It's very hot")
print("Drink plenty of water")

This prints:

Drink plenty of water

It isn't hot, so Python skips the block. But print("Drink plenty of water") isn't part of it, so it runs even at 20 degrees.

The opposite mistake, indenting a line that doesn't belong to any block, ends with an error: IndentationError: unexpected indent. And all the lines of one block must be indented by the same number of spaces, so stick to 4.

Instructions

The program tells you to plug in the charger even when the battery is at 80. Indent the line print("Plug in the charger") by 4 spaces, so that it belongs to the block of the if statement. Then the program prints only Battery: 80.

Change battery to 15 and run the program. Now the condition is true, and the program prints all three lines: Low battery, Plug in the charger and Battery: 15.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

2/15

Next