Codiqo

Learn Python · lesson 13 of 60 · about 7 minutes

if and else

Turn the assistant's True or False into advice: make it choose what to do with if and else, and learn why indentation matters.

What you'll learn

  • Run code only when a condition is True
  • Provide an alternative with else
  • Indent blocks correctly

Telling Sam what to do

Your assistant works out can_buy, but then it only prints True or False. Sam wants advice: go and get the bike, or keep saving. The script needs to do one thing or the other, depending on the answer.

Making a choice

if runs a block of code only when its condition is True. The line ends with a colon :, and the code that belongs to it is indented (4 spaces is the standard).

else gives the other path: it runs when the condition is False.

One path or the other

temperature = 8
if temperature < 10:
    print("Wear a coat.")
else:
    print("T-shirt weather!")
print("Have a good day.")

Output

Wear a coat.
Have a good day.

Advice instead of True or False

can_buy = False
if can_buy:
    print("Go and get the bike!")
else:
    print("Keep saving for now")

Output

Keep saving for now

Indentation is part of the code

In many languages indentation is just style. In Python it decides which lines belong to the if. The last print above isn't indented, so it always runs.

Several lines in one block

coins = 120
if coins >= 100:
    print("You can afford the hat!")
    coins -= 100
print(f"Coins left: {coins}")

Output

You can afford the hat!
Coins left: 20

Empty counts as False

The condition doesn't have to be a comparison. False, 0, empty text "" and None all count as False in an if, and almost everything else counts as True. So if task: means if there's a task.

Tip

Forgetting the colon at the end of an if line is the most common Python error. If you see SyntaxError: expected ':', check there first.

Now try it yourself

This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.