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")[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]))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 endingPlan your program here, then type it in and press Run.
step, and a constant at the top.patrol, and return the list as well as the count.beep_count to go_home that beeps once per step, without any global variables.