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.
Worked examples
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.
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.
A taste of the worksheets
These are some of the questions on the sets. The printable sheets have more and an answer key.
- Which rule has no else? š„Ŗ if you are hungry, eat lunch, else keep playing / š¦ if the light is green, go, else wait / ā if it rains, take an umbrella
- Which rule has an else? š if the bell rings, line up / š” if the lamp is dark, turn it on / š if the bridge is clear, cross it, else use the stones
- Which rule has no else? šµ if the soil is dry, water it / š if the bridge is clear, cross it, else use the stones / š„Ŗ if you are hungry, eat lunch, else keep playing
- Which rule has an else? ā if it rains, take an umbrella / š¦ if the light is green, go, else wait / š” if the lamp is dark, turn it on
- Which rule has no else? š if the bell rings, line up / š§„ if it is cold, wear a coat, else wear a shirt / š¦ if the light is green, go, else wait
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 for
- 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?
Else. Else covers the case when the answer is no.
Can an if-else run both of its parts?
No. It always picks exactly one.
Does if it rains, take an umbrella have an else?
No. It does nothing at all when it does not rain.
If it is sunny, walk to school, else take an umbrella. It is sunny. What happens?
You walk to school. The then part runs and the else part is skipped.
Two if-else forks in a row. How many paths in all?
2. Each fork picks one path.
For grown-ups
With 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.
Do 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.