🎯 What you will learn
- A while loop repeats while a rule is true
- The robot checks the sensor each time
- Stopping safely is part of the design
👋 Let’s get started!
Some robots keep moving until something gets in the way. A while loop repeats as long as a rule is true. When the wall gets too close, the rule becomes false and the robot stops. 🧱
🪜 Step by step
1. 🔁 while
A while loop keeps going as long as its question is true.
distance = 3
while distance > 0:
print("Still going")
2. 📉 Change a value
Each move makes the distance smaller. That changes the answer to the question.
distance = distance - 1
3. 🛑 Stop
When the question is false, the loop ends and the robot stops.
print("Stop! Wall!")
🧪 Try it!
Change the code and press ▶ Run to see what happens. You can’t break anything!
Approach the wall
distance = 30
while distance > 10:
print("Moving. Distance:", distance)
distance = distance - 8
print("Stop! Wall close:", distance)🎨 Unplugged activity
🧱 With a grown-up, count down from 10 out loud while taking a step each time. What number does the loop stop at? Make a rule for when to stop.
Build a safe loop
distance = 20
while distance > 5:
print("Move")
distance = distance - 5
print("Stop")📖 Key words
Tap a card to flip it over!
- while
- Repeat while a rule is true 🔁
- Condition
- The question checked each time ❓
- Obstacle
- Anything in the way 🧱
🏆 Challenge
Make the robot count down from 3 and print “Go!” when it reaches 0. Press ▶ Run.
Challenge
count = 3
Knowledge Check Quiz
- When does a while loop stop?
- What does distance = distance – 8 do?
- What happens if the distance never gets small?