The answersDownload the PDF
Worksheet

F4.1 Writing functions

Functions and structured code · GCSE · OCR J277 2.2.3, AQA 8525 3.2.10, Edexcel 1CP2 1.1.2 · about 12 min

BugBotLab
NameClassDate

What this lesson is about

def, calling, and why subprograms help.

Questions 6 marks in all

  1. [1 mark]What happens when Python reaches def report(): and its indented body?

    1. AIt defines the function, but nothing in the body runs yet
    2. BIt runs the body once
    3. CIt runs the body forever
    4. DIt prints report
  2. [1 mark]Which are good reasons to write a function?

    Tick every answer that is true.

    1. AWrite a piece of behaviour once and reuse it
    2. BA name like is_clear(40) explains what the code does
    3. CSmall pieces are easier to test
    4. DIt makes the robot faster
  3. [1 mark]What does this program print?

    def signal():
        print("  beep")
    
    print("before")
    signal()
    print("between")
    signal()
  4. [1 mark]A program calls signal() on line 3 and defines def signal(): on line 5. What happens?

    1. ANameError: the function is not defined yet when line 3 runs
    2. BIt works, Python looks ahead
    3. CSyntaxError
    4. DNothing is printed and there is no error
  5. [1 mark]What is a subprogram?

    1. AA named block of code that does a task and can be called from elsewhere in the program
    2. BA program that runs on another computer
    3. CA comment above some code
    4. DThe first line of a program
  6. [1 mark]In OCR's Exam Reference Language, which word ends a procedure? (one word)

The task: signal at the corners

Write a function signal() that turns the LED red, plays a short note, and turns the LED off. Then drive a square of 25 cm sides, calling signal() at every corner. Call your function; do not repeat its lines.

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

def signal():
    led("red")

forward(60, distance=25)
turn_right(30, angle=90)

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

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

Challenges

  1. Write siren() that alternates two notes four times, and call it at the start and the end of a drive.
  2. Put the four side() calls inside a function square(), and call square() twice.
  3. What happens if you call a function inside itself? Try it with a function that only prints, and read the error.