Functions and structured code · GCSE · OCR J277 2.2.3, AQA 8525 3.2.10, Edexcel 1CP2 1.1.2 · about 12 min
def, calling, and why subprograms help.
[1 mark]What happens when Python reaches def report(): and its indented body?
[1 mark]Which are good reasons to write a function?
Tick every answer that is true.
[1 mark]What does this program print?
def signal():
print(" beep")
print("before")
signal()
print("between")
signal()before beep between beep
At each call the program jumps into the function, runs its body, and comes back to the next line.
[1 mark]A program calls signal() on line 3 and defines def signal(): on line 5. What happens?
[1 mark]What is a subprogram?
[1 mark]In OCR's Exam Reference Language, which word ends a procedure? (one word)
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)The hint students can ask for: Write the signal once as a function, then call it at each corner from a loop that drives and turns.
from bugbot import *
connect()
def signal():
led("red")
tone(880, 0.2)
led("off")
for i in range(4):
forward(60, distance=25)
signal()
turn_right(30, angle=90)
Any program that meets the task's checks is marked correct in the simulator; this is one way, not the only way.