KS4J277 2.2.3 34 min read 10 question quiz 19 exam marks

Additional Programming Techniques

Strings, arrays, file handling, SQL, subroutines and random numbers. This is the widest single topic on Paper 2 and the one with the most easy marks available.

String manipulation

OperationOCR reference languagePython
Lengthname.lengthlen(name)
Substringname.substring(2,3)name[2:5]
Uppercasename.uppername.upper()
Lowercasename.lowername.lower()
Left charactersname.left(3)name[:3]
Right charactersname.right(3)name[-3:]
Joinfirst + " " + lastfirst + " " + last
OCR substring takes a start and a LENGTH

"Computing".substring(3,4) starts at index 3 and takes 4 characters, giving puti. Python slicing takes a start and an END index, so "Computing"[3:7] also gives puti. Read the question carefully to see which is being used.

Common patterns

Python
# Build a username from a name
first = "Aisha"
last = "Khan"
username = (first[0] + last).lower()      # akhan

# Count the vowels in a word
word = input("Enter a word: ")
count = 0
for letter in word.lower():
    if letter in "aeiou":
        count = count + 1
print("Vowels:", count)

# Reverse a string
print(word[::-1])

# Check a palindrome
clean = word.lower().replace(" ", "")
if clean == clean[::-1]:
    print("Palindrome")
A string is a row of characters, each with an indexThe word Computer drawn as eight letter tiles. Above each tile is its index, counting from 0 at the first letter to 7 at the last, and below it is the negative index, counting back from the end, from minus 8 to minus 1. A slice takes part of the string: word, bracket, 0, colon, 3 gives Com, which runs from index 0 up to but not including index 3, and word, bracket, 3, colon gives puter, from index 3 to the end. word minus one is the last character, r. Below, four things you can do with a string: len gives the number of characters, which is 8; upper gives a new string in capitals; find gives the index of the first match, here 3 for the letter p; and a plus sign joins two strings together. A string is never changed in place: each of these gives back a new string.indexfrom the endC0-8o1-7m2-6p3-5u4-4t5-3e6-2r7-1word[0:3] = "Com"word[3:] = "puter"word[-1] = "r"123len(word)8how many charactersword.upper()"COMPUTER"a new string in capitalsword.find("p")3index of the first matchword + "s""Computers"+ joins two strings4
  1. Every character has an index. The first is 0, and negative indexes count back from the end.
  2. A slice [a:b] runs from index a up to, but not including, b. Leave b out to go to the end.
  3. [-1] is the last character.
  4. Functions and methods build and search strings, and each one gives back a new string.
In exam pseudocode the same idea is written as substring: check your board's command set for the exact form.
Six string methods applied to the text with spaces round Hello World, and why the original never changesSix string methods applied to text equal to two spaces, Hello World, two spaces. upper gives all capitals. strip removes the spaces at the ends, giving Hello World. replace of l with capital L swaps every match, giving HeLLo WorLd with its spaces. strip then split on a space breaks the text into the list Hello, World. join of the list a, b, c with a hyphen builds the text a-b-c. find of World gives 8, the position where it starts. On the right a reminder that strings do not change: text dot upper makes a brand new string and leaves text as it was, so to keep the result you assign it, name equals name dot upper. Split and join are opposites.text = "  Hello World  "1text.upper()"  HELLO WORLD  "2text.strip()"Hello World"3text.replace("l", "L")"  HeLLo WorLd  "4text.strip().split(" ")["Hello", "World"]5"-".join(["a", "b", "c"])"a-b-c"6text.find("World")8Strings are fixed7textstays the sametext.upper() makesa brand new stringnew stringkeep it by assigning:name = name.upper()split and join are opposites: split breaks text into a list, join builds text from a list.
  1. upper() makes every letter a capital.
  2. strip() removes spaces from both ends.
  3. replace() swaps every match for something else.
  4. split() breaks a string into a list.
  5. join() builds a string from a list.
  6. find() gives the position of the first match, or -1 if there is none.
  7. A method returns a new string. The original is never changed unless you assign the result.
Methods return new strings. To keep the result, assign it to a variable.

Arrays and lists

An array stores many values of the same type under one name, accessed by an index starting at 0.

Python
scores = [12, 45, 3, 78, 20]

print(scores[0])        # 12, the first item
print(scores[4])        # 20, the last item
print(len(scores))      # 5

scores[2] = 99          # change the third item
scores.append(60)       # add to the end

Working through an array

Python
total = 0
highest = scores[0]

for value in scores:
    total = total + value
    if value > highest:
        highest = value

print("Total:", total)
print("Average:", total / len(scores))
print("Highest:", highest)

Notice highest is initialised to the first element, not to 0. Initialising to 0 breaks if all the values are negative.

Two dimensional arrays

A 2D array is a grid, accessed with two indexes: row then column.

Python
board = [["X", "O", "X"],
         ["O", "X", "O"],
         ["X", "O", "X"]]

print(board[1][2])      # row 1, column 2, which is "O"

for row in board:
    for cell in row:
        print(cell, end=" ")
    print()
Row first, then column

board[1][2] means row 1, column 2. Getting these the wrong way round is a classic exam error, especially in non square grids.

A list is a row of numbered lockersA list drawn as a row of numbered lockers, with the code that changes it. The list scores starts with five values, 72, 85, 90, 64 and 78, in lockers numbered from 0. The call append of 88 adds a new locker on the end, so the list now has six items. The assignment scores, bracket, 1, bracket, equals 99 replaces what was in locker 1, the 85, with 99. Reading scores bracket 2 opens locker 2 and finds 90, and len of scores is 6, so the last index is 5, one less than the length. The program prints 90 and 6.lists.py1scores = [72, 85, 90, 64, 78]2scores.append(88)3scores[1] = 994print(scores[2], len(scores))output90 6the item at index 2, then the length720991902643784885appendchangedscores[2]len(scores) is 6, so the last index is 51234
  1. The list holds its items in order, and the first locker is number 0.
  2. append() puts a new item on the end, so the list grows.
  3. Assign to an index to replace what is there. The old value is gone.
  4. scores[2] opens locker 2. len(scores) counts the lockers, so the last index is one less.
Index from 0, and remember the last index is len minus 1.

File handling

Programs need to store data between runs, and that means reading from and writing to files.

Python
# Writing to a file
file = open("scores.txt", "w")      # "w" overwrites the whole file
file.write("Aisha,42
")
file.write("Ben,37
")
file.close()

# Appending, which adds without deleting what is there
file = open("scores.txt", "a")
file.write("Chris,55
")
file.close()

# Reading the whole file line by line
file = open("scores.txt", "r")
for line in file:
    parts = line.strip().split(",")
    name = parts[0]
    score = int(parts[1])
    print(name, "scored", score)
file.close()

The three modes

ModeMeaning
"r"Read. Fails if the file does not exist.
"w"Write. Creates the file, and erases everything already in it.
"a"Append. Creates the file if needed, and adds to the end.
Opening in "w" mode destroys the file contents

If a question asks you to add a record without losing existing data, you must use append mode. This is a common mark.

Always close the file when finished, so that data is properly written and the file is released.

OCR reference language

OCR reference language
myFile = open("scores.txt")
while NOT myFile.endOfFile()
    print(myFile.readLine())
endwhile
myFile.close()
Reading, writing and appending to a text fileThree ways to open a text file, one card each. Opening with mode r reads the file: the program looks at the lines, nothing in the file changes, and it is an error if the file does not exist. Opening with mode w writes: it creates the file if it is missing, but if it exists everything in it is erased first, so a file that held two lines ends up holding only the new line. Opening with mode a appends: the new line is added to the end and the old lines are kept. The code below uses the with statement, which closes the file automatically, and writes the line Tia comma 51 followed by a newline character. Always close a file, because unwritten data may stay in a buffer and never reach the disk."r" readbeforeAsha,42Tom,37"w" writebeforeAsha,42Tom,37"a" appendbeforeAsha,42Tom,37programreads each linethe file is not changederror if it does not existTia,51erases what was therecreates the file if missingAsha,42Tom,37Tia,51adds to the endkeeps what was theresave.py1with open("scores.txt", "a") as f:2    f.write("Tia,51\n")with closes the file for you\n starts a new linea is safer than w for addingalways close a file, or the last lines may never reach the disk1234
  1. r reads. The file is only looked at, and it must already exist.
  2. w writes. Everything already in the file is erased first.
  3. a appends. New lines go on the end and the old ones are kept.
  4. with closes the file for you, and \n ends a line.
If you mean to add to a file, open it with a. Opening it with w by mistake wipes it.

SQL

SQL, Structured Query Language, is used to search and manipulate data in a database. J277 requires SELECT, FROM and WHERE.

SELECT which columns you want FROM which table WHERE which rows to include

Examples

Given a table called Students:

StudentIDNameYearGrade
1Aisha119
2Ben106
3Chloe118

Select everything:

SQL
SELECT * FROM Students

Select specific columns:

SQL
SELECT Name, Grade FROM Students

Select with a condition:

SQL
SELECT Name FROM Students WHERE Year = 11

Multiple conditions:

SQL
SELECT Name FROM Students WHERE Year = 11 AND Grade >= 8

Text values need quotation marks, numbers do not:

SQL
SELECT * FROM Students WHERE Name = 'Aisha'
The asterisk means all columns

SELECT * returns every column. If the question asks only for names, use SELECT Name or you may lose the mark for precision.

An SQL query labelled clause by clause, and what each clause does to the tableAn SQL query is read clause by clause. SELECT name, mark chooses which columns. FROM results says which table. WHERE mark greater than 60 chooses which rows. ORDER BY mark DESC puts them in order, highest first. Applied to a table of five pupils, id, name and mark, WHERE drops Ben on 55 and Eli on 48 and keeps three rows. SELECT keeps only the name and mark columns. ORDER BY puts the result in order: Chloe 91, Aisha 72 and Dev 64.query.sqlSELECT name, markFROM resultsWHERE mark > 60ORDER BY mark DESC;which columnswhich tablewhich rowsin what order1The table: results2idnamemark1Aisha722Ben553Chloe914Dev645Eli48WHERE mark > 60 keeps 3 rows and drops 2The result3namemarkChloe91Aisha72Dev64only the two chosen columns,highest mark first
  1. Each clause has a job: SELECT picks columns, FROM names the table, WHERE picks rows, ORDER BY sorts.
  2. WHERE keeps the rows that meet the condition and drops the rest.
  3. The result has only the selected columns, in the order asked for.
Read a query in the order FROM, WHERE, SELECT, ORDER BY: pick the table, filter the rows, choose the columns, then sort.

Subroutines and random numbers

Subroutines

A subroutine is a named block of code that performs a specific task and can be called from anywhere in a program.

Python
def calculate_area(width, height):
    return width * height          # a FUNCTION, it returns a value

def show_welcome(name):
    print("Welcome,", name)        # a PROCEDURE, it returns nothing

area = calculate_area(5, 3)        # area is 15
show_welcome("Aisha")

Parameters are the variables listed in the definition. Arguments are the actual values passed in when it is called.

Why subroutines matter

  • Avoid repetition. Write the code once and call it many times.
  • Easier to test. Each subroutine can be tested on its own.
  • Easier to maintain. Fix a bug in one place rather than in ten copies.
  • Reusable in other programs.
  • Support decomposition, since each sub problem becomes a subroutine.
  • Improve readability, because a well named call explains itself.

Local and global variables

A local variable exists only inside the subroutine where it is created. A global variable is available throughout the whole program.

Local variables are preferred because they cannot be changed accidentally by other parts of the program, and their memory is freed when the subroutine finishes.

Random numbers

Python
import random

dice = random.randint(1, 6)          # a whole number from 1 to 6 inclusive
card = random.choice(["A", "K", "Q"]) # a random item from a list
OCR reference language
dice = random(1, 6)

Random numbers are used in games, simulations, shuffling, sampling and generating test data.

A function takes values in and hands a value backA function drawn as a machine. The code defines area with two parameters, w and h, and returns w times h. The line x equals area of 3, 4 calls it: the two arguments, 3 and 4, drop into the machine through the hopper, and the result, 12, comes out of the chute and is stored in x, so print of x shows 12. Parameters are the names the function uses for what it is given, and arguments are the actual values supplied when it is called. Below, a procedure and a function are compared: a procedure does a job, such as printing a greeting, and gives nothing back, while a function hands a value back to the caller with return.area.py1def area(w, h):2    return w * h34x = area(3, 4)5print(x)output12A function is a machinearea(w, h)34arguments in12returnedw and h:parametersProceduredef hello():    print("Hi")does a job, givesnothing backFunctiondef double(n):    return n * 2hands a value backwith return1234
  1. Define it once with def, naming the parameters it will be given.
  2. Call it with arguments. They fill the parameters, w = 3 and h = 4.
  3. return hands the result back to the line that called it.
  4. A procedure does a job. A function also gives a value back.
Parameters are the names in the definition. Arguments are the values in the call.

Key terms you must be able to define

Array
A data structure holding many values of the same type under one name, accessed by index.
Index
The position of an item within an array, counting from 0.
2D array
An array of arrays, forming a grid accessed by row and column.
Subroutine
A named block of code that performs a specific task and can be called from elsewhere.
Parameter
A variable listed in a subroutine definition that receives a value when it is called.
Argument
The actual value passed into a subroutine when it is called.
Local variable
A variable that only exists within the subroutine in which it is declared.
Global variable
A variable available to every part of the program.
Concatenation
Joining strings together end to end.
SQL
Structured Query Language, used to search and manipulate data in a database.
Append mode
Opening a file so that new data is added to the end without erasing existing content.

Flashcards

Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.

DefineArray
AnswerA data structure holding many values of the same type under one name, accessed by index.
DefineIndex
AnswerThe position of an item within an array, counting from 0.
Define2D array
AnswerAn array of arrays, forming a grid accessed by row and column.
DefineSubroutine
AnswerA named block of code that performs a specific task and can be called from elsewhere.
DefineParameter
AnswerA variable listed in a subroutine definition that receives a value when it is called.
DefineArgument
AnswerThe actual value passed into a subroutine when it is called.
DefineLocal variable
AnswerA variable that only exists within the subroutine in which it is declared.
DefineGlobal variable
AnswerA variable available to every part of the program.

Reach the top grade on this topic

This topic covers a lot of ground, so target the marks that are most reliably available.

SQL is nearly free marks. Three keywords, one structure. Learn SELECT ... FROM ... WHERE ... and practise ten queries. Quote text values, do not quote numbers, and only select the columns you were asked for.

File modes matter. If the question says add a record without losing existing data, the answer is append mode. Write mode erases the file.

Explain subroutines by benefit, not definition. "A subroutine avoids repeating the same code, so if the calculation changes it only has to be edited in one place, which reduces the chance of introducing errors."

Initialise from the data, not from zero. When finding a maximum or minimum in an array, start from the first element. This is a favourite exam trap.

  • Write a SELECT query with a WHERE clause for any given table
  • Read a file line by line and split each line into fields
  • Write a function and call it, and explain why it is a function not a procedure
  • Loop through a 2D array using row and column indexes in the right order

Mistakes that cost marks here

Avoid these
  • Opening a file in write mode when the question requires existing data to be kept.
  • Forgetting to close a file after use.
  • Using SELECT * when the question asked for specific columns.
  • Putting quotation marks around a number in an SQL WHERE clause.
  • Getting row and column the wrong way round in a 2D array.
  • Initialising a maximum to 0 rather than to the first element of the array.
  • Forgetting that array indexes start at 0, so the last index is length minus 1.
Fun fact

Almost every real program spends most of its time manipulating strings and reading files. The glamorous algorithms get the attention, but text processing is what software actually does all day.

Knowledge check

0 of 10 answered
1What does "Programming"[0:4] produce in Python?
2An array data has 8 elements. What is the index of the last element?
3Which file mode adds data to the end of a file without deleting what is already there?
4Which SQL query returns only the names of students in Year 11?
5What is the difference between a parameter and an argument?
6In the 2D array grid, how would you access the item in row 2, column 0?
7Why are local variables generally preferred to global variables?
8What does random.randint(1, 6) return?
9Which is a benefit of using subroutines?
10A program needs to find the largest value in an array that may contain negative numbers. How should the variable holding the maximum be initialised?
Score 0 / 10

Exam-style questions

Five written questions in the style of the real paper. Write a full answer, then let the marker check it against the mark scheme.

19 marks
1Write an SQL query to return the Name and Grade of all students in the table Students who have a Grade of 7 or higher.3 marks
Write

Mark scheme0 / 3
  • LUses SELECT with the correct columns Name and Grade
  • LUses FROM with the correct table name
  • LUses WHERE with the correct condition
Model answer

SELECT Name, Grade FROM Students WHERE Grade >= 7 The SELECT clause names the two columns required rather than using an asterisk, FROM names the table being queried, and WHERE restricts the rows returned to those where the Grade column holds a value of 7 or above. No quotation marks are used around 7 because it is a number, not text.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2Explain two benefits of using subroutines in a program.4 marks
Explain

Mark scheme0 / 4
  • LCode that is needed in several places is written only once
  • LIf a change is needed it is made in one place, reducing errors
  • LEach subroutine can be tested independently
  • LPrograms are easier to read and understand, and subroutines support decomposition
Model answer

The first benefit is the removal of duplication. Code that is needed in several parts of a program can be written once as a subroutine and then called wherever it is needed, which makes the program shorter. More importantly, if that code ever needs correcting or updating, the change only has to be made in one place, rather than finding and editing every copy, which greatly reduces the risk of leaving an old version behind and introducing a bug. The second benefit is that subroutines make a program much easier to develop and test. Each subroutine handles one clearly defined task, so it can be tested on its own with a range of inputs until it is known to work correctly, and different programmers can develop different subroutines at the same time. This also makes the main program far easier to read, because a well named call such as calculateTotalCost explains what is happening without the reader needing to see the detail.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3A program stores high scores in a text file. Explain why the file should be opened in append mode rather than write mode when a new score is added.3 marks
Explain

Mark scheme0 / 3
  • LWrite mode erases the existing contents of the file
  • LAll previous high scores would therefore be lost
  • LAppend mode adds the new score to the end while keeping existing data
Model answer

Opening a file in write mode causes the existing contents of that file to be erased before anything new is written, so every high score already stored would be permanently lost as soon as a single new score was saved. Append mode instead opens the file so that anything written is added to the end, leaving all the existing content untouched. Since the purpose of a high score table is to accumulate results over time, append mode is the correct choice.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4Write a program that reads a list of names from a file called names.txt and outputs only those names that begin with the letter A.5 marks
Write

Mark scheme0 / 5
  • LOpens the file for reading
  • LUses a loop to process each line
  • LRemoves the newline character or otherwise cleans the line
  • LTests whether the first character is A
  • LOutputs matching names and closes the file
Model answer

file = open("names.txt", "r") for line in file: name = line.strip() if name[0].upper() == "A": print(name) file.close() The file is opened in read mode and each line is processed in turn. The strip method removes the newline character from the end of each line so that the name is clean. The first character of the name is converted to uppercase and compared with A, so that names beginning with either a capital or a lowercase a are matched, and matching names are printed. The file is closed once every line has been processed.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5Explain the difference between a local variable and a global variable, and state one reason why local variables are usually preferred.4 marks
Explain

Mark scheme0 / 4
  • LA local variable only exists inside the subroutine where it is declared
  • LA global variable is accessible throughout the whole program
  • LLocal variables cannot be changed accidentally by other parts of the program
  • LMemory used by a local variable is freed when the subroutine ends
Model answer

A local variable is declared inside a subroutine and only exists while that subroutine is running, so it cannot be seen or changed by any code outside it. A global variable is declared outside all subroutines and is accessible from anywhere in the program, so any part of the code can read or modify it. Local variables are usually preferred because their limited scope prevents them being altered accidentally by unrelated parts of the program, which removes a very common and hard to trace source of bugs, and it also means two subroutines can safely use the same variable name without interfering with each other. In addition, the memory a local variable occupies is released as soon as the subroutine finishes, whereas a global variable takes up memory for the entire time the program runs.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 19