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)[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)[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)Plan your program here, then type it in and press Run.
global steps. Then list what a reader of step now has to check that they did not before.creep in the first cell take the speed as a parameter instead of reading the global SPEED. What does that make easier to test?print(beeps) just before beeps = beeps + 1 in the second cell. Why does that line fail too, when reading a global normally works?