if raining: say("Take an umbrella")if in code
Now the robot makes choices in code. A choice starts with if. The if line ends with a colon. The line under it is indented. It runs only when the if is true.
if raining: say("Take an umbrella") else: say("Wear a hat")else in code
Add else for the other choice. Raining? It says Take an umbrella. Not raining? It says Wear a hat. Only one of the two lines runs.
if raining: say("Umbrella") say("Bye")Lines after the choice
say("Bye") is not indented. It is not part of the choice. So it always runs. Raining: Umbrella, then Bye. Not raining: just Bye.
if blocked_right(): move_down() else: move_right()The robot asks questions
The robot can check its board. on_star() asks: am I on a star? blocked_right() asks: is the way right blocked? Robot questions end with two brackets.
- repeat 3 timesif the way right is blockedmove downelsemove right
Watch the robot choose
This robot uses the rule above 3 times. A rock blocks its second step right. So it goes down instead. Then the way is clear, so it goes right.
For parents
Goal: Your child learns to read if and else in code and tell which line runs.
- Ask: is the if true or not true? Then point to the line that runs.
- Point out lines that are not indented. They run either way.
- The labs ask your child to predict a choice, fix an else, then build an if and else rule. Open See it as code to read the same program as real code.
Away from the screen: Write "if sunny: play outside, else: read a book" on a card. Check the weather each morning and follow the code together.