Skip to content
Book 8: Algorithms, Programming and Databases

Book 8 · Chapter 10

Further programming and testing

§10.1§10.2§10.3§10.4§10.5Exam craftB8·10

This 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.

Open in the ebook

§10.1 Variables and constants

Short code B8·10·1

§10.2 Procedures and functions

Short code B8·10·2

§10.3 Lists

Short code B8·10·3

§10.4 File handling

Short code B8·10·4

§10.5 Testing

Short code B8·10·5

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 and local, side by side. Notice 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
Run and checked before printing
count = 0

def add_one():
    count = count + 1

add_one()
print(count)
Changing a global without the global keyword. Python stops with a run-time error on line 4.
Run and checked before printing
score = 10

def reset():
    score = 0
    print("Inside:", score)

reset()
print("Outside:", score)
Assigning to a name inside a function makes a new local variable. The global score is untouched.

Output

Inside: 0
Outside: 10
Run and checked before printing

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)
Two procedures and a function. Notice that 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
------------
Run and checked before printing
def area(length, width):
    return length * width

print(area(6, 4))
The Mark Ladder's function, run.

Output

24
Run and checked before printing

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))
The named functions on one list of goals. Notice 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
Run and checked before printing
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))
A thousand random numbers from each function. Notice the top value: randint includes its end value, randrange stops one before it.

Output

randint: 1 to 6
randrange: 1 to 5
Run and checked before printing

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")
The trace-it program, run.

Output

Day 1 22
Day 3 25
2 warm days
Run and checked before printing
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())
Two ways to fill a list, and two ways to go through it. Inputs: Ali, Bina, Chen, then 7, 9, 4.

Output

Ali 7
Bina 9
Chen 4
ALI
BINA
CHEN
Run and checked before printing

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))
Every list method and operator the syllabus names, on one list. Read each line of output beside the statement that made it.

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
Run and checked before printing
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]
Run and checked before printing

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)
A 2D list: row first, then column. Notice total = 0 sits inside the outer loop, so it restarts for each student.

Output

Bina test 2: 14
Ali 36
Bina 49
Chen 37
Run and checked before printing
grid = []
for row in range(3):
    grid.append([0, 0, 0, 0])
grid[1][2] = 5
for row in range(3):
    print(grid[row])
Building a 2D list with a loop: each append adds a new, separate row.

Output

[0, 0, 0, 0]
[0, 0, 5, 0]
[0, 0, 0, 0]
Run and checked before printing
grid = [[0, 0, 0, 0]] * 3
grid[1][2] = 5
for row in range(3):
    print(grid[row])
The shortcut that goes wrong: one change appears in every row.

Output

[0, 0, 5, 0]
[0, 0, 5, 0]
[0, 0, 5, 0]
Run and checked before printing
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)
The Mark Ladder's answer, run on four weeks of data.

Output

Week 1 26
Week 2 30
Week 3 14
Week 4 32
Run and checked before printing
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)
The faded twin's answer: the loops change places.

Output

Day 1 27
Day 2 15
Day 3 13
Day 4 3
Day 5 12
Day 6 22
Day 7 10
Run and checked before printing

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"))
Linear search as a function. return ends the function at the first match; -1 means not found.

Output

2
-1
Run and checked before printing
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])
Bubble sort on a 2D list, by the points in column 1, highest first. Notice that whole rows are swapped, so each team keeps its own points.

Output

Eagles 19
Hawks 15
Lions 12
Bears 7
Run and checked before printing

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)
Write, append, then read. Notice that "w" makes a new file and "a" adds to the end of it.

Output

Ali,12
Bina,18
Chen,15
Run and checked before printing
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
Run and checked before printing
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)
Numbers in a file: str() on the way in, int() on the way out. Inputs: 12, 18, 15.

Output

Total: 45
Run and checked before printing

Output

Tuesday
Run and checked before printing
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")
The Mark Ladder's answer (the second part), run on a three-line file that the first part writes.

Output

What is 2 + 2?
Name a primary colour.
How many days in a week?
3 lines
Run and checked before printing

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"))
Five validation checks, each a function that returns True or False. Each output line tests one check with a value it accepts, or refuses, and one it does not.

Output

True False
True False
True False
False True
True False
True False
Run and checked before printing
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")
Validation with re-input. Inputs: 0, 12, then 3.

Output

Error: enter a number from 1 to 8
Error: enter a number from 1 to 8
Booked 3 tickets
Run and checked before printing
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")
A type check before the range check. Inputs: two, 9, then 3. Because 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
Run and checked before printing
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"))
One common way to make a check digit (weights 4, 3, 2 and remainder after dividing by 11). The typing slip changes the digit, so it is caught.

Output

573 gets the check digit 8
Typed 5378: digit should be 1
Run and checked before printing
temp = int(input())
while temp <= -10 or temp >= 50:
    print("Error: must be above -10 and below 50")
    temp = int(input())
print("Accepted", temp)
The faded twin's answer, run with 50, -10, then 49. Both limits are refused, because the range is exclusive.

Output

Error: must be above -10 and below 50
Error: must be above -10 and below 50
Accepted 49
Run and checked before printing

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)
A double entry check. The first pair differs by two swapped letters, so both are asked for again.

Output

No match. Type both again.
Saved: sana@mail.pk
Run and checked before printing

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))
The test data in the table, run through the check. Each line is a test value and whether it was accepted.

Output

7 True
2 True
12 True
1 False
13 False
40 False
Run and checked before printing

Errors and debugging

Short code B8·10·22

scores = [14, 9, 11]
print(scores[3])
A run-time error: there is no item at index 3.
Run and checked before printing

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))
Hard to maintain: it runs, but what is it for?

Output

5.333333333333333
Run and checked before printing
# 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))
The same program, easy to maintain. Notice that the output is exactly the same.

Output

5.333333333333333
Run and checked before printing

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.

Ask Z about Further programming and testing
Buy ZAK's books — WhatsApp the books desk: Buy the booksPrint or ebook