Decisions and loops · GCSE · about 25 min
A while loop, decisions and the buzzer: beep faster as the wall gets closer, and park.
[1 mark]Why does the parking sensor use a while loop rather than a for loop?
[1 mark]What does this program print?
d = 35
if d > 50:
gap = 0.4
elif d > 30:
gap = 0.25
else:
gap = 0.1
print(gap)0.25
35 is not over 50, but it is over 30, so the second branch runs.
[1 mark]The robot stops slightly closer to the wall than BAY. Why?
[1 mark]Where must beeps = 0 go?
Drive to the wall, beeping faster as it gets closer, and stop in the green bay without touching the wall. Then play a long note, turn the LED red and print one line in exactly this shape (your numbers will differ):
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
BAY = 20
beeps = 0
while distance() > BAY:
forward(30)
wait(0.1)
stop()The hint students can ask for: Each time round the loop: move a little, read the gap, and choose the pause between beeps from that gap. Count the beeps as you go, and do the stopping, the long tone and the report after the loop ends.
from bugbot import *
connect()
BAY = 20
beeps = 0
while distance() > BAY:
forward(30)
d = distance()
if d > 50:
gap = 0.4
elif d > 30:
gap = 0.25
else:
gap = 0.1
tone(880, 0.05)
wait(gap)
beeps = beeps + 1
stop()
tone(880, 1)
led("red")
print("stopped", distance(), "cm from the wall after", beeps, "beeps")
Any program that meets the task's checks is marked correct in the simulator; this is one way, not the only way.