The answersDownload the PDF
Worksheet

F4.3 Local and global variables

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

BugBotLab
NameClassDate

What this lesson is about

Scope: where a variable exists, and why passing values beats global.

Questions 6 marks in all

  1. [1 mark]A function sets gap = 10 inside its body. After calling it, the program runs print(gap). What happens?

    1. ANameError: gap only exists while the function runs
    2. BIt prints 10
    3. CIt prints gap
    4. DIt prints nothing
  2. [1 mark]What does this program print?

    speed = 80
    
    def gentle():
        speed = 30
        print(speed)
    
    gentle()
    print(speed)
  3. [1 mark]beeps = 0 outside, and inside a function beeps = beeps + 1 with no global line. What happens when the function runs?

    1. AUnboundLocalError: assigning makes beeps local, and it has no value yet
    2. Bbeeps becomes 1
    3. CThe global beeps becomes 1
    4. DNameError
  4. [1 mark]Which are reasons local variables are good practice?

    Tick every answer that is true.

    1. AA subprogram can be understood and tested on its own
    2. BThe same names can be used safely in different subprograms
    3. CThe memory is freed when the subprogram ends
    4. DThey make the program run without errors
  5. [1 mark]What does this program print?

    count = 0
    
    def add():
        global count
        count = count + 1
    
    add()
    add()
    print(count)
  6. [1 mark]What is the scope of a variable?

    1. AThe part of the program where it can be used
    2. BThe largest value it can hold
    3. CIts data type
    4. DHow long its name is

The task: count the beeps

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)

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

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

Challenges

  1. Write longest_so_far(reading, best) that returns whichever is larger, and use it in a loop of readings without any global variables.
  2. Add a global constant NOTE = 660 and use it inside beep. Why does reading it work without global?
  3. Find a program from an earlier lesson that uses variables inside a function, and say which are local and which are global.