🎯 Syllabus & Goals 3 min
Cambridge 8.1.6 · Local and global variables 8.1.7 · Library routines 8.1.8 · Maintainable programs Paper 2
By the end of this lesson you can:
- Describe the difference between local and global variables, and predict the output of a program that uses both.
- Use the library routines
MOD,DIV,ROUNDandRANDOMin pseudocode and Python. - Make a program maintainable with meaningful identifiers, subroutines and comments.
Textbook: Chapter 8, §8.1.6–8.1.8 (pp. 325–329)
Recap / Warm-Up 5 min
Last lesson: procedures (called with CALL) and functions (which RETURN a value). Today: where their variables can be seen, and the ready-made routines every language provides.
Quick starter
A procedure declares DECLARE Counter : INTEGER inside itself. Can the main program output Counter after the procedure has finished?
Reveal the answer
No. Counter is local to the procedure — it only exists while the procedure runs. The main program gets an error.
🧠 Key Concept 14 min
1 · Local and global variables (scope)
Counter without any clash.2 · Library routines
A programming language's development system includes a library of ready-made, fully tested procedures and functions. You call them instead of writing your own. The string operations in Lesson 5 were library routines. You must be able to use these four:
random must be imported first.To get a random whole number in pseudocode, scale and round the result of RANDOM():
// a whole number from 1 to 6 DiceRoll ← ROUND(RANDOM() * 5, 0) + 1 // a whole number from 0 to 100 Percent ← ROUND(RANDOM() * 100, 0)
import random dice_roll = random.randint(1, 6) # 1 to 6 inclusive percent = random.randint(0, 100)
3 · Creating a maintainable program
A program is often updated later — by another programmer, or by you years later with no memory of it. A maintainable program:
- always uses meaningful identifiers for variables, constants, arrays, procedures and functions;
- is divided into modules — procedures and functions — each doing one task;
- is fully commented (
//in pseudocode,#in Python).
Worked Example 12 min
Example 1 · Predicting output with local and global variables
Cambridge pseudocode
DECLARE Score : INTEGER PROCEDURE AddBonus DECLARE Bonus : INTEGER Bonus ← 50 Score ← Score + Bonus OUTPUT "Bonus added: ", Bonus ENDPROCEDURE Score ← 100 CALL AddBonus OUTPUT "Score is now ", Score OUTPUT "Bonus is ", Bonus
The same in Python
# Global and local variables score = 100 # global: declared in the main program def add_bonus(): global score # Python must be told to change the global bonus = 50 # local: exists only inside add_bonus score = score + bonus print("Bonus added:", bonus) add_bonus() print("Score is now", score) print("Bonus is", bonus) # error: bonus is local to add_bonus
Bonus added: 50 Score is now 150 NameError: name 'bonus' is not defined
Scoreis global, set to 100 in the main program.declared outside every subroutine.- Inside
AddBonus, the localBonusis 50 and the globalScorebecomes 150.a procedure can read and change a global. - After the call,
Scoreis still 150 — butBonusno longer exists.locals are destroyed when their subroutine ends, so the last line is an error.
A local variable can even have the same name as a global — it is a separate store, and the global is untouched:
# A local variable can share a global's name without changing it total = 500 # global def test(): total = 7 # a NEW local variable called total print("Inside test, total is", total) test() print("In the main program, total is still", total)
Inside test, total is 7 In the main program, total is still 500
Example 2 · Library routines in a dice game
Roll two dice five times, output each roll, and output the average total to one decimal place.
Cambridge pseudocode
// Dice game: five rolls of two dice CONSTANT NumberOfRolls ← 5 DECLARE Roll, Die1, Die2, GrandTotal : INTEGER DECLARE Average : REAL GrandTotal ← 0 FOR Roll ← 1 TO NumberOfRolls Die1 ← ROUND(RANDOM() * 5, 0) + 1 Die2 ← ROUND(RANDOM() * 5, 0) + 1 OUTPUT "Roll ", Roll, ": ", Die1, " + ", Die2, " = ", Die1 + Die2 GrandTotal ← GrandTotal + Die1 + Die2 NEXT Roll Average ← GrandTotal / NumberOfRolls OUTPUT "Average total: ", ROUND(Average, 1)
The same in Python
import random # Dice game: roll two dice five times and report the average total NUMBER_OF_ROLLS = 5 grand_total = 0 for roll in range(1, NUMBER_OF_ROLLS + 1): die1 = random.randint(1, 6) die2 = random.randint(1, 6) print("Roll", roll, ":", die1, "+", die2, "=", die1 + die2) grand_total = grand_total + die1 + die2 average = grand_total / NUMBER_OF_ROLLS print("Average total:", round(average, 1))
Output — one possible run (different every time)
Roll 1 : 2 + 5 = 7 Roll 2 : 5 + 2 = 7 Roll 3 : 3 + 5 = 8 Roll 4 : 4 + 6 = 10 Roll 5 : 5 + 1 = 6 Average total: 7.6
Check the maths: 7 + 7 + 8 + 10 + 6 = 38, and 38 ÷ 5 = 7.6. Quick checks of library results in Python:
import random # the library that holds random() print(10 % 3) # MOD print(10 // 3) # DIV print(round(6.97354, 2)) # ROUND to 2 decimal places print(random.random()) # RANDOM: a real number from 0 to 1 print(random.randint(1, 6)) # a whole number from 1 to 6
1 3 6.97 0.32383276483316237 2
Example 3 · Making a program maintainable
Both programs below give the same answer. Only one could be safely updated by someone else.
Hard to maintain
p = float(input("$")) x = round(p * 1.2, 2) print(x)
Maintainable
# Shop bill: works out VAT and the total to pay VAT_RATE = 0.2 # 20% tax, change here only def add_vat(price): # Returns the price with VAT added, rounded to 2 decimal places return round(price * (1 + VAT_RATE), 2) item_price = float(input("Enter the price before VAT: $")) price_to_pay = add_vat(item_price) print("Price including VAT: $", price_to_pay)
Enter the price before VAT: $19.99 Price including VAT: $ 23.99
pandxbecameitem_priceandprice_to_pay.meaningful identifiers say what each store holds.- The bare
1.2became the constantVAT_RATE.if the tax changes, one line is edited. - The calculation moved into a function with a comment.a module does one job and can be tested and re-used on its own.
Try It Yourself 12 min
Goal: State the value of: MOD(25, 7), DIV(25, 7), ROUND(3.14159, 3), ROUND(8.5, 0). Then check them in Python and explain any difference you see.
Goal: Write a program that generates a random whole number from 100 to 300, then inputs two integers A and B and outputs MOD(A, B) and DIV(A, B).
Goal: Write a number-guessing game: the computer picks 1–50; the user guesses until correct, being told "higher" or "lower"; the number of guesses is output. Use a function for the random pick, meaningful names, a constant for the top number and comments.
Hint
A REPEAT … UNTIL Guess = Secret loop fits, because the user must guess at least once. Count guesses inside the loop. In Python, build it with while True and break.
📝 Exam Practice 10 min
Describe, using examples, the difference between local and global variables.
Mark scheme
- A global variable can be accessed by any part of the program / its scope is the whole program (1).
- e.g. a variable declared in the main program, such as
Score, used inside a procedure (1). - A local variable can only be accessed in the subroutine / block where it is declared (1).
- e.g. a loop counter declared inside a procedure cannot be used by the main program (1).
Explain why programmers find library routines useful. Include two examples of library routines in your answer.
Mark scheme
- They are already written, so they save development time (1).
- They are already fully tested, so they are reliable / less likely to contain errors (1).
- Two examples from: MOD, DIV, ROUND, RANDOM, LENGTH, SUBSTRING, UCASE, LCASE (1 + 1).
State three ways a programmer can make a program easier to maintain.
Mark scheme
- Use meaningful identifiers for variables / constants / arrays / subroutines (1).
- Divide the program into modules / procedures and functions (1).
- Add comments to explain the code (1).
- Accept: use constants for fixed values; use indentation / white space.
Write a pseudocode statement to store in Mean the value of Total / Count rounded to 2 decimal places, and one to store in Lucky a random whole number from 0 to 10.
Mark scheme
Mean ← ROUND(Total / Count, 2)(1)- Use of
RANDOM()multiplied by 10 (1)… - …and rounded to a whole number:
Lucky ← ROUND(RANDOM() * 10, 0)(1)
🗝️ Recap & Key Terms 3 min
Scope is where a variable can be used: globals everywhere, locals only inside their subroutine. Library routines — MOD, DIV, ROUND, RANDOM — are pre-written and tested. Maintainable programs use meaningful names, modules and comments.
- Global variable
- A variable that can be used by any part of a program; its scope covers the whole program.
- Local variable
- A variable that can only be used by the part of the program it is declared in.
- Library routine
- A ready-made, fully tested procedure or function supplied with a language's development system.
- ROUND
- A library routine that rounds a value to a given number of decimal places.
- RANDOM
- A library routine that generates a random number (between 0 and 1 in pseudocode).
- Maintainable program
- A program that another programmer can understand and update: meaningful identifiers, modules and comments.
Homework 1 min
Task (≤ 15 min): State the output of this algorithm, line by line. [4]
DECLARE A, B : INTEGER PROCEDURE Change DECLARE B : INTEGER A ← A * 2 B ← 99 OUTPUT "Inside: ", A, " ", B ENDPROCEDURE A ← 5 B ← 8 CALL Change OUTPUT "Outside: ", A, " ", B
Model answer
Inside: 10 99 Outside: 10 8
- Inside: A is global and doubles to 10 (1); B is the local B = 99 (1).
- Outside: A stays 10 because the global was changed (1); B is still 8 because only the local B was set (1).