The big ideaAn if-else asks one question and then does exactly one of two things.
How it works
An if-else asks one question and then does exactly one of two things.
If the answer is yes, the then part runs. If the answer is no, the else part runs.
Never both, and never neither.
After the if-else, the two paths meet again and the program carries on.
One run of an if-else.
Example 1: If on its own
Kai's rule is if the bridge is clear, cross it.
A branch lies across the bridge, so the if is false.
The rule says nothing at all, so Bo waits at the edge.
Example 2: Add an else
Kai's new rule is if the bridge is clear, cross it, else hop over the stones.
The bridge is not clear, so Bo does the else part.
He hops over the stepping stones and the lemonade stays steady.
Line 3 is the else.
Example 3: A clear bridge
The next day the bridge is clear.
Bo takes the then part and skips the else part.
Never both, and never neither.
Example 4: Two forks
Bo meets two if-else forks in a row.
Each one picks exactly one path.
So Bo takes 2 paths in all, one for each fork.
Words to know
if-else
A rule that asks one question and picks one of two paths.
else
The part that runs when the answer is no.
then part
The part that runs when the answer is yes.
Watch out
An if on its own does nothing when it is false. Add an else for the other case.
An if-else never runs both parts. It always picks one.
Yes runs the first part. The else part waits.
Both paths meet again, so the program carries on after the fork.
Try it
The answer is no. Which part runs, then or else?
Can an if-else run both of its parts?
Does if it rains, take an umbrella have an else?
If it is sunny, walk to school, else take an umbrella. It is sunny. What happens?
Two if-else forks in a row. How many paths in all?
Answers: 1. Else · 2. No · 3. No · 4. You walk to school · 5. 2
Try at homeWith a grown-up, make three if-else rules, like: if it is sunny, then walk to school, else take an umbrella. Say the question, the then part and the else part. No screen needed.
For grown-upsDo the Mission: make three if-else rules for your day together, like if it is sunny then walk to school else take an umbrella. Say the question, the then part and the else part. No screen needed.
Open these notes on screenScan the code, or go to tutorpip.com.