Book 8 · Chapter 10
Further programming and testing
B8·10This chapter is in the ebook.
Read it in full on cswithzak.com. Every question has its mark scheme and every program is ready to run. The free practice for each section is below, with the short code the book prints beside it.
For the whole chapter
- Topic pageFurther programming and testing (2029–2031)
B8·10·T - QuizFurther programming and testing
B8·10·Q1 - LabPython example py29-local-global
B8·10·X1 - LabPython example py-scope
B8·10·X2 - LabPython example py-functions
B8·10·X3 - LabPython example py29-library-functions
B8·10·X4 - LabPython example py-lists
B8·10·X5 - LabPython example py29-list-methods
B8·10·X6 - LabPython example py-2d-list
B8·10·X7 - LabPython example py-linear-search
B8·10·X8 - LabPython example py-bubble-sort
B8·10·X9 - LabPython example py29-file-modes
B8·10·X10 - LabPython example py-file-write-read
B8·10·X11 - LabPython example py-file-eof
B8·10·X12 - LabPython example py29-validation-checks
B8·10·X13 - LabPython example py-validation
B8·10·X14 - LabPython example py29-double-entry
B8·10·X15 - LabPython example py29-logic-error
B8·10·X16 - LabPython example py29-scenario-sports-day
B8·10·X17
§10.1 Variables and constants
Short code B8·10·1
- FlashcardsFlashcards §10.1: Local and global variables and constants
B8·10·F1
§10.2 Procedures and functions
Short code B8·10·2
- FlashcardsFlashcards §10.2: Procedures, functions & built-in functions
B8·10·F2
§10.5 Testing
Short code B8·10·5
- FlashcardsFlashcards §10.5: Validation and verification
B8·10·F5 - FlashcardsFlashcards §10.5: Test data, errors & maintainable code
B8·10·F6
Local and global variables
Short code B8·10·10
# global constant: used in more than one place
TAX_RATE = 0.2
# global variable: the running total
basket = 0.0
def add_item(cost):
global basket
LIMIT = 50.0 # local constant
if cost > LIMIT:
print("Too expensive:", cost)
else:
basket = basket + cost
def with_tax(amount):
tax = amount * TAX_RATE # local variable
return amount + tax
add_item(12.5)
add_item(70.0)
add_item(7.5)
print("Basket:", basket)
print("With tax:", with_tax(basket))global basket: without it, the procedure could read basket but not change it.Output
Too expensive: 70.0 Basket: 20.0 With tax: 24.0
count = 0
def add_one():
count = count + 1
add_one()
print(count)global keyword. Python stops with a run-time error on line 4.score = 10
def reset():
score = 0
print("Inside:", score)
reset()
print("Outside:", score)score is untouched.Output
Inside: 0 Outside: 10
Constants, local and global
Short code B8·10·11
Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.
Procedures and functions
Short code B8·10·12
# a procedure with one parameter
def show_line(length):
line = ""
for i in range(length):
line = line + "-"
print(line)
# a function: it returns a value
def area(width, height):
return width * height
# a procedure with no parameters
def title():
print("Room planner")
title()
show_line(12)
room = area(4, 3)
print("Kitchen:", room)
print("Both rooms:", area(4, 3) + area(5, 2))
show_line(12)area(4, 3) can be used inside an expression, because it hands back a value; show_line(12) cannot.Output
Room planner ------------ Kitchen: 12 Both rooms: 22 ------------
def area(length, width):
return length * width
print(area(6, 4))Output
24
Python's ready-made functions
Short code B8·10·13
import statistics
goals = [2, 0, 3, 1, 3, 4, 3]
print("Total:", sum(goals))
print("Games with 3 goals:", goals.count(3))
print("Most:", max(goals), "Fewest:", min(goals))
average = statistics.mean(goals)
print("Mean:", average)
print("Mean to 1 d.p.:", round(average, 1))
print("Mean to a whole number:", round(average))import statistics at the top, and the dot in goals.count(3) and statistics.mean(goals).Output
Total: 16 Games with 3 goals: 3 Most: 4 Fewest: 0 Mean: 2.2857142857142856 Mean to 1 d.p.: 2.3 Mean to a whole number: 2
import random
dice = []
cards = []
for i in range(1000):
dice.append(random.randint(1, 6))
cards.append(random.randrange(1, 6))
print("randint:", min(dice), "to", max(dice))
print("randrange:", min(cards), "to", max(cards))randint includes its end value, randrange stops one before it.Output
randint: 1 to 6 randrange: 1 to 5
Lists: one name, many values
Short code B8·10·14
temps = [18, 22, 15, 25]
warm = 0
for day in range(len(temps)):
if temps[day] > 20:
warm = warm + 1
print("Day", day, temps[day])
print(warm, "warm days")Output
Day 1 22 Day 3 25 2 warm days
names = [] # an empty list
for i in range(3):
names.append(input())
scores = [0] * 3 # three items, each 0
for i in range(3):
scores[i] = int(input())
for i in range(3):
print(names[i], scores[i])
for name in names: # each item, no index
print(name.upper())Output
Ali 7 Bina 9 Chen 4 ALI BINA CHEN
Working with lists
Short code B8·10·15
queue = ["Asha", "Bilal", "Chen"]
queue.append("Dina")
print(queue)
queue.insert(1, "Eli")
print(queue)
last = queue.pop()
print("pop() gave", last, queue)
first = queue.pop(0)
print("pop(0) gave", first, queue)
queue.sort()
print("sort():", queue)
queue.sort(reverse=True)
print("sort(reverse=True):", queue)
print("Eli" in queue, "Asha" not in queue, len(queue))
marks = [55, 72, 61]
print(sum(marks), max(marks), min(marks))Output
['Asha', 'Bilal', 'Chen', 'Dina'] ['Asha', 'Eli', 'Bilal', 'Chen', 'Dina'] pop() gave Dina ['Asha', 'Eli', 'Bilal', 'Chen'] pop(0) gave Asha ['Eli', 'Bilal', 'Chen'] sort(): ['Bilal', 'Chen', 'Eli'] sort(reverse=True): ['Eli', 'Chen', 'Bilal'] True True 3 188 72 55
marks = [55, 72, 61]
result = marks.sort()
print(result)
print(marks).sort() changes the list itself and hands back nothing (None).Output
None [55, 61, 72]
Two-dimensional lists
Short code B8·10·16
# each row: [name, test 1, test 2, test 3]
results = [["Ali", 12, 15, 9],
["Bina", 18, 14, 17],
["Chen", 10, 11, 16]]
print(results[1][0], "test 2:", results[1][2])
for row in range(len(results)):
total = 0
for col in range(1, 4):
total = total + results[row][col]
print(results[row][0], total)total = 0 sits inside the outer loop, so it restarts for each student.Output
Bina test 2: 14 Ali 36 Bina 49 Chen 37
grid = []
for row in range(3):
grid.append([0, 0, 0, 0])
grid[1][2] = 5
for row in range(3):
print(grid[row])append adds a new, separate row.Output
[0, 0, 0, 0] [0, 0, 5, 0] [0, 0, 0, 0]
grid = [[0, 0, 0, 0]] * 3
grid[1][2] = 5
for row in range(3):
print(grid[row])Output
[0, 0, 5, 0] [0, 0, 5, 0] [0, 0, 5, 0]
rain = [[0, 4, 12, 0, 3, 0, 7],
[5, 5, 0, 0, 0, 18, 2],
[0, 0, 1, 0, 9, 4, 0],
[22, 6, 0, 3, 0, 0, 1]]
for week in range(4):
total = 0
for day in range(7):
total = total + rain[week][day]
print("Week", week + 1, total)Output
Week 1 26 Week 2 30 Week 3 14 Week 4 32
rain = [[0, 4, 12, 0, 3, 0, 7],
[5, 5, 0, 0, 0, 18, 2],
[0, 0, 1, 0, 9, 4, 0],
[22, 6, 0, 3, 0, 0, 1]]
for day in range(7):
total = 0
for week in range(4):
total = total + rain[week][day]
print("Day", day + 1, total)Output
Day 1 27 Day 2 15 Day 3 13 Day 4 3 Day 5 12 Day 6 22 Day 7 10
Searching and sorting a list
Short code B8·10·17
def find(names, target):
index = 0
while index < len(names):
if names[index] == target:
return index
index = index + 1
return -1
members = ["Omar", "Lina", "Ravi", "Sara"]
print(find(members, "Ravi"))
print(find(members, "Zoe"))return ends the function at the first match; -1 means not found.Output
2 -1
teams = [["Lions", 12], ["Eagles", 19],
["Bears", 7], ["Hawks", 15]]
swapped = True
while swapped:
swapped = False
for i in range(len(teams) - 1):
if teams[i][1] < teams[i + 1][1]:
temp = teams[i]
teams[i] = teams[i + 1]
teams[i + 1] = temp
swapped = True
for team in teams:
print(team[0], team[1])Output
Eagles 19 Hawks 15 Lions 12 Bears 7
Files: data that lasts
Short code B8·10·18
# "w" creates the file, or empties it first
with open("scores.txt", "w") as file:
file.write("Ali,12\n")
file.write("Bina,18\n")
# "a" adds to the end of the file
file = open("scores.txt", "a")
file.write("Chen,15\n")
file.close()
# "r" reads; .read() gives one string
with open("scores.txt", "r") as file:
text = file.read()
print(text)Output
Ali,12 Bina,18 Chen,15
with open("names.txt", "w") as file:
file.write("Ali\n")
file.write("Bina\n")
file.write("Chen\n")
with open("names.txt", "r") as file:
first = file.readline()
second = file.readline()
print("First:", first.replace("\n", ""))
print("Second:", second.replace("\n", ""))
with open("names.txt", "r") as file:
lines = file.readlines()
print(lines)
print(len(lines), "lines")readline() and readlines(). Notice the \n at the end of each item that readlines() returns.Output
First: Ali Second: Bina ['Ali\n', 'Bina\n', 'Chen\n'] 3 lines
with open("marks.txt", "w") as file:
for i in range(3):
mark = int(input())
file.write(str(mark) + "\n")
total = 0
with open("marks.txt", "r") as file:
for line in file.readlines():
total = total + int(line)
print("Total:", total)str() on the way in, int() on the way out. Inputs: 12, 18, 15.Output
Total: 45
Output
Tuesday
with open("quiz.txt", "w") as file:
file.write("What is 2 + 2?\n")
file.write("Name a primary colour.\n")
file.write("How many days in a week?\n")
count = 0
with open("quiz.txt", "r") as file:
for line in file.readlines():
print(line.replace("\n", ""))
count = count + 1
print(count, "lines")Output
What is 2 + 2? Name a primary colour. How many days in a week? 3 lines
Validation: is the data sensible?
Short code B8·10·19
DIGITS = "0123456789"
# range, inclusive: 0 and 100 allowed
def in_range(mark):
return mark >= 0 and mark <= 100
# range, exclusive: 11 and 19 refused
def in_age_range(age):
return age > 11 and age < 19
# length: exactly 6 characters
def right_length(code):
return len(code) == 6
# presence: not left empty
def is_present(name):
return name != ""
# type: digits only
def is_whole_number(text):
if text == "":
return False
for character in text:
if character not in DIGITS:
return False
return True
# format: 2 capital letters, then 4 digits
def right_format(code):
if len(code) != 6:
return False
for i in range(6):
if i < 2:
if code[i] < "A" or code[i] > "Z":
return False
elif code[i] not in DIGITS:
return False
return True
print(in_range(100), in_range(101))
print(in_age_range(12), in_age_range(19))
print(right_length("AB1234"), right_length("AB12"))
print(is_present(""), is_present("Sana"))
print(is_whole_number("42"), is_whole_number("4.2"))
print(right_format("KT2041"), right_format("kt2041"))Output
True False True False True False False True True False True False
tickets = int(input())
while tickets < 1 or tickets > 8:
print("Error: enter a number from 1 to 8")
tickets = int(input())
print("Booked", tickets, "tickets")Output
Error: enter a number from 1 to 8 Error: enter a number from 1 to 8 Booked 3 tickets
DIGITS = "0123456789"
def is_whole_number(text):
if text == "":
return False
for character in text:
if character not in DIGITS:
return False
return True
text = input()
while (not is_whole_number(text) or int(text) < 1
or int(text) > 8):
print("Enter a whole number from 1 to 8")
text = input()
tickets = int(text)
print("Booked", tickets, "tickets")or stops at the first True, int(text) is never tried on "two".Output
Enter a whole number from 1 to 8 Enter a whole number from 1 to 8 Booked 3 tickets
def check_digit(code):
total = 0
weight = 4
for i in range(3):
total = total + int(code[i]) * weight
weight = weight - 1
return (11 - total % 11) % 11
print("573 gets the check digit", check_digit("573"))
print("Typed 5378: digit should be", check_digit("537"))Output
573 gets the check digit 8 Typed 5378: digit should be 1
temp = int(input())
while temp <= -10 or temp >= 50:
print("Error: must be above -10 and below 50")
temp = int(input())
print("Accepted", temp)Output
Error: must be above -10 and below 50 Error: must be above -10 and below 50 Accepted 49
Verification: was it copied correctly?
Short code B8·10·20
email = input()
again = input()
while email != again:
print("No match. Type both again.")
email = input()
again = input()
print("Saved:", email)Output
No match. Type both again. Saved: sana@mail.pk
Test data
Short code B8·10·21
def valid_guests(guests): # 2 to 12 inclusive
return guests >= 2 and guests <= 12
for guests in [7, 2, 12, 1, 13, 40]:
print(guests, valid_guests(guests))Output
7 True 2 True 12 True 1 False 13 False 40 False
Errors and debugging
Short code B8·10·22
scores = [14, 9, 11]
print(scores[3])Programs that are easy to maintain
Short code B8·10·23
a=[3,8,5]
b=0
for c in a:
b=b+c
print(b/len(a))Output
5.333333333333333
# Works out the mean of a team's scores
def mean_score(scores):
total = 0
for score in scores:
total = total + score
return total / len(scores)
team_scores = [3, 8, 5]
print(mean_score(team_scores))Output
5.333333333333333
Command-word coach
Short code B8·10·24
Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.
Workbook: Further programming and testing
Short code W8·10 · Algorithms, Programming and Databases Workbook
The write-in workbook for this chapter has drills, exam-style practice, trace tables, fix-the-mistake and mark-it-yourself pages. Its full mark schemes and an interactive version arrive here with the chapter.
Starter files
Short code W8·10·K
Data files and skeleton code in Python for this chapter's tasks arrive here with the chapter.


