Programming techniques and object-oriented programming · A level · OCR H446 2.2.1, AQA 7517 4.1.1.13, Eduqas A500QS 1.8 · about 20 min
Local and global variables, why locals are good practice, and breakpoints, stepping, watches and tracebacks.
[1 mark]What is the lifetime of a local variable?
[1 mark]What does this program print?
speed = 80
def slow():
speed = 30
return speed
print(slow(), speed)30 80
The assignment inside slow makes a new local speed; the global speed is still 80.
[1 mark]Why is it good practice to use local variables rather than global variables in subroutines?
Tick every answer that is true.
[1 mark]A program gives the wrong total, but only on the 40th time round a loop. Which IDE feature lets you run at full speed and then pause at the line that updates the total?
[1 mark]What does this program print?
total = 0
def add(n):
global total
total = total + n
add(5)
add(7)
print(total)12
global makes total inside add refer to the global variable, so both calls change it.
[1 mark]An exception is not handled and Python prints a traceback. What does the traceback show?
This program should creep towards the wall in 5 cm steps while distance() is more than 25, then print steps: <n>, the number of steps taken. It stops with an UnboundLocalError. Run it and read the message first.
Fix it without global: give step a parameter, count (the number of steps so far, an integer), and make it return count + 1, with the main program assigning the result back. Add a watch line: before each move, step prints step <n>: <cm> cm, where <n> is the number of the step about to be taken (1 for the first) and <cm> is the value distance() returns.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
steps = 0
def step():
forward(50, distance=5)
steps = steps + 1
while distance() > 25:
step()
print("steps:", steps)The hint students can ask for: Read the error message: it names the variable and says it is local. The function only needs the count in and the new count out, so give it a parameter and a return value, and let the caller keep the result.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
def step(count):
print(f"step {count + 1}: {distance()} cm")
forward(50, distance=5)
return count + 1
steps = 0
while distance() > 25:
steps = step(steps)
print("steps:", steps)
Any program that meets the task's checks is marked correct in the simulator; this is one way, not the only way.