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.
How Python chooses.
Example 1: The else path
The box holds sun: weather = "sun".
Python checks weather == "rain". It is false.
Python skips the umbrella line and runs the else line.
Bo says: Wear a hat.
Example 2: The if path
Now the box holds rain: weather = "rain".
The condition weather == "rain" is true.
Python runs the line under if, and skips else.
Bo says: Take an umbrella.
Example 3: Reading a condition
The box coins holds 7, and the condition is coins > 5.
Is seven bigger than five? Yes, so the condition is true.
The condition coins < 5 is false, because seven is not smaller than five.
Example 4: A mix-up with equals
The line if weather = "rain": uses one equals sign.
One equals sign puts a value in a box, so it does not ask a question.
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
One equals sign stores a value. Two equals signs ask. Mixing them up is a very common bug, and even experts do it.
An if line ends with a colon, and so does else.
Text in a condition needs quotes: weather == "rain", not weather == rain.
Lines pushed in belong to the if. Pushing them in is not only to look neat.
Try it
The box stars holds 4. Is stars == 4 true or false?
The box weather holds snow. Is weather != "snow" true or false?
The box coins holds 7. Is coins >= 8 true or false?
Does else run when the condition is true or when it is false?
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.