Functions and structured code · GCSE · OCR J277 2.2.3, AQA 8525 3.2.10, Edexcel 1CP2 6.6.3 · about 15 min
Scope: where a variable exists, and why passing values beats global.
[1 mark]A function sets gap = 10 inside its body. After calling it, the program runs print(gap). What happens?
[1 mark]What does this program print?
speed = 80
def gentle():
speed = 30
print(speed)
gentle()
print(speed)30 80
The speed inside the function is a new local variable, so the global speed is unchanged.
[1 mark]beeps = 0 outside, and inside a function beeps = beeps + 1 with no global line. What happens when the function runs?
[1 mark]Which are reasons local variables are good practice?
Tick every answer that is true.
[1 mark]What does this program print?
count = 0
def add():
global count
count = count + 1
add()
add()
print(count)2
global count means the function changes the global variable, so two calls make it 2.
[1 mark]What is the scope of a variable?
This program should beep three times and print beeps: 3, but it crashes. Fix it, with parameters and return or with global.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
beeps = 0
def beep():
tone(880, 0.1)
wait(0.1)
beeps = beeps + 1
beep()
beep()
beep()
print("beeps:", beeps)The hint students can ask for: A function cannot change a variable made outside it unless you say so. Either pass the count in and hand the new one back, or declare the outside variable global at the top of the function. Pick one and keep it consistent.
from bugbot import *
connect()
def beep(count):
tone(880, 0.1)
wait(0.1)
return count + 1
beeps = 0
beeps = beep(beeps)
beeps = beep(beeps)
beeps = beep(beeps)
print("beeps:", beeps)
Any program that meets the task's checks is marked correct in the simulator; this is one way, not the only way.