Tutorpip← About this lessonOpen the sheet →Download PDF
Ages 10+ · Coding · Python
If in Python
If the weather is rain• if weather == "rain":•   print("Take an umbrella")Otherwise• else:•   print("Wear a hat")
One program, two paths.
The big ideaIf runs lines only when a condition is true. Else runs when it is false.

How it works

A computer chooses by asking a question that is only ever true or false. That question is called a condition.

If runs its lines only when the condition is true. Else runs when the condition is false.

Two equals signs ask whether two things are equal. One equals sign puts a value in a box.

The colon after if, and the lines pushed in under it, show which lines belong to the if.

Check the conditionTrue: run the linesunder ifFalse: run the linesunder else
How Python chooses.

Example 1: The else path

  1. The box holds sun: weather = "sun".
  2. Python checks weather == "rain". It is false.
  3. Python skips the umbrella line and runs the else line.
  4. Bo says: Wear a hat.

Example 2: The if path

  1. Now the box holds rain: weather = "rain".
  2. The condition weather == "rain" is true.
  3. Python runs the line under if, and skips else.
  4. Bo says: Take an umbrella.

Example 3: Reading a condition

  1. The box coins holds 7, and the condition is coins > 5.
  2. Is seven bigger than five? Yes, so the condition is true.
  3. The condition coins < 5 is false, because seven is not smaller than five.

Example 4: A mix-up with equals

  1. The line if weather = "rain": uses one equals sign.
  2. One equals sign puts a value in a box, so it does not ask a question.
  3. The mix-up to fix: use two equals signs, if weather == "rain":.

Words to know

condition
A question that is only ever true or false.
if
Runs its lines only when the condition is true.
else
Runs its lines when the condition is false.
indented
Pushed in, to show which lines belong to the if.

Watch out

Try it

  1. The box stars holds 4. Is stars == 4 true or false?
  2. The box weather holds snow. Is weather != "snow" true or false?
  3. The box coins holds 7. Is coins >= 8 true or false?
  4. Does else run when the condition is true or when it is false?
  5. Which asks whether two things are equal: one equals sign or two?
Answers: 1. True · 2. False · 3. False · 4. When it is false · 5. Two equals signs
Try at homeWith a grown-up, play the if game. They call out the weather. If it is rain, you act out putting on a coat. Else, you act out putting on sunglasses. Then ask them to invent a third rule, with its own condition.
For grown-upsPlay the if game: call out the weather, and your child acts out a coat for rain and sunglasses for everything else. Then ask them to invent a third rule with its own condition.
Open these notes on screenScan the code, or go to tutorpip.com.