The answersDownload the PDF
Worksheet

F4.6 Project: the patrol

Functions and structured code · GCSE · about 25 min

BugBotLab
NameClassDate

What this lesson is about

A complete program built a function at a time: patrol to the wall and come home.

Questions 5 marks in all

  1. [1 mark]Why test step(n) on its own before writing the loop?

    1. AMistakes are easiest to find while the program is small
    2. BPython needs functions to be run once first
    3. CIt charges the battery
    4. DThe loop will not work otherwise
  2. [1 mark]What does a name written in capitals, like STOP_AT = 30, tell someone reading the program?

    1. AIt is set once and not changed while the program runs
    2. BPython will not let it change
    3. CIt is a function
    4. DIt is printed automatically
  3. [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")
  4. [1 mark]In the patrol, why does patrol(stop_at) return the number of steps rather than print it?

    1. Ago_home needs the value to drive back the same distance
    2. BPrinting is not allowed in functions
    3. Creturn is faster
    4. DSo nothing appears on screen
  5. [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]))

The task: patrol

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 ending

Plan your program here, then type it in and press Run.

QR code
Do it on the robot
www.bugbotlab.com/learn/f4-6-project-the-patrol/
The simulator checks it and tells you when it passes. Nothing to install, no account.

Challenges

  1. Make the step size a parameter of step, and a constant at the top.
  2. Store every distance reading in a list inside patrol, and return the list as well as the count.
  3. Add a beep_count to go_home that beeps once per step, without any global variables.