Functions and structured code · GCSE · about 25 min
A complete program built a function at a time: patrol to the wall and come home.
[1 mark]Why test step(n) on its own before writing the loop?
[1 mark]What does a name written in capitals, like STOP_AT = 30, tell someone reading the program?
[1 mark]What does this program print?
n = 1
while n <= 3:
print(f"step {n}")
n = n + 1
print("stopped after", n - 1, "steps")step 1 step 2 step 3 stopped after 3 steps
The counter goes up after every step, so when the loop ends n is one more than the number of steps.
[1 mark]In the patrol, why does patrol(stop_at) return the number of steps rather than print it?
[1 mark]What does this program print?
def patrol(readings):
n = 0
for d in readings:
if d <= 30:
break
n = n + 1
return n
print(patrol([60, 50, 40, 30, 20]))3
It counts steps until a reading is 30 or less: 60, 50 and 40 count, then it stops.
Build the patrol against the wall: drive in 10 cm steps while the wall is more than 30 cm away, printing step <n>: <distance> cm each time; then print arrived, turn the LED green, and be inside the green zone.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
def step(n):
forward(50, distance=10)
print(f"step {n}: {distance()} cm")
# the loop, then the endingThe hint students can ask for: Write one function for a single step that drives a little and reports where the wall is. Call it from a loop that keeps going while the wall is still far enough away, then finish with the arrival message and the LED.
from bugbot import *
connect()
def step(n):
forward(50, distance=10)
print(f'step {n}: {distance()} cm')
n = 1
while distance() > 30:
step(n)
n = n + 1
print('arrived')
led('green')
Any program that meets the task's checks is marked correct in the simulator; this is one way, not the only way.