Additional programming techniques
String handling, arrays, files, records, SQL, sub-programs and random numbers.
Learning Objectives
- 1Manipulate strings, including concatenation and slicing
- 2Use 1D and 2D arrays to solve problems, understanding they are fixed-length structures
- 3Use records and 2D arrays to represent database-style tables of fields
- 4Use basic file handling operations: open, read, write, close
- 5Use SQL (SELECT, FROM, WHERE) to search for data
- 6Use functions and procedures, including parameters, local and global variables
- 7Generate random numbers in a program
String manipulation
+) and slicing (extracting part of a string). In OCR's Exam Reference Language, subject.length gives the number of characters, subject.substring(x, i) extracts i characters starting at position x (0-indexed), .left(i) and .right(i) get the first/last i characters, and .upper/.lower convert case.subject.substring(x, i), remember x is the starting index and i is the number of characters to extract, not an end index, a common error is to treat the second argument as an end position.subject = "ComputerScience"
print(len(subject)) # 15
print(subject[3:8]) # "puter" (substring: start 3, 5 chars)
print(subject[:4]) # "Comp" (left 4)
print(subject[-3:]) # "nce" (right 3)
print(subject.upper()) # "COMPUTERSCIENCE"
greeting = "Hi" + " there" # concatenationsubject = "ComputerScience"
print(subject.length) // 15
print(subject.substring(3,5)) // "puter"
print(subject.left(4)) // "Comp"
print(subject.right(3)) // "nce"
print(subject.upper) // "COMPUTERSCIENCE"
greeting = "Hi" + " there" // concatenationOne-dimensional (1D) arrays
colours[1] accesses the second item in the array.scores = [10, 20, 30]
print(scores[1]) # 20
scores[0] = 15array scores = [10, 20, 30]
print(scores[1]) // 20
scores[0] = 15Two-dimensional (2D) arrays
gameboard[1,0] (both indexes inside one set of square brackets, separated by a comma).seating[0,1], while Python uses two separate pairs of brackets (a list of lists), e.g. seating[0][1]. Both mean the same thing: row 0, item 1 within that row. Know which syntax you're using and stay consistent.seating = [["Adam", "Aleks"], ["Krish", "Tom"]]
print(seating[0][1]) # "Aleks"array seating = [["Adam", "Aleks"], ["Krish", "Tom"]]
print(seating[0,1]) // "Aleks"Records
student = ["Aleks", 10, True] # one record: name, year group, has-paid
print(student[0]) # "Aleks" (the first field)array student = ["Aleks", 10, True] // one record: name, year group, has-paid
print(student[0]) // "Aleks" (the first field)File handling
myFile = open("sample.txt"), myFile.readLine(), myFile.writeLine("text"), and myFile.close()..endOfFile() can be used in a loop condition to keep reading lines until the end of the file is reached, without knowing in advance how many lines it contains.my_file = open("sample.txt", "r")
line = my_file.readline()
while line:
print(line)
line = my_file.readline()
my_file.close()myFile = open("sample.txt")
while NOT myFile.endOfFile()
print(myFile.readLine())
endwhile
myFile.close()SQL: searching a database
SELECT <field(s)> FROM <table> WHERE <condition>. Multiple fields are separated by commas, and the wildcard * means "all fields". String values in a WHERE condition must be enclosed in quotation marks, e.g. WHERE Day = "Saturday".# SQL is written the same way regardless of host language
query = 'SELECT Model FROM Cars WHERE Sold = False'SELECT Model
FROM Cars
WHERE Sold = FalseFunctions and procedures
returns a value, which should be used (e.g. stored in a variable) by the code that called it. A procedure carries out a task, such as printing something, but does not return a value. Choosing between them: use a function where the calling code needs a value back to store or use in a further calculation, and a procedure where the task is complete in itself. Use a sub-program at all wherever the same task is needed in more than one place, or where a long program would be clearer broken into named steps.return its result rather than printing it, and the code that calls the function must actually use the returned value (typically by assigning it to a variable), rather than redefining or recalculating it separately. Using sub-programs effectively means splitting a program at points where a task is genuinely self-contained and reused, so each sub-program has one clear job, can be tested on its own, and can be called from anywhere it is needed rather than the same code being written out repeatedly.def ticket_price(tickets): # function: returns a value
return tickets * 12.50
total = ticket_price(3)
print(total)
def greet(name): # procedure: does a task, returns nothing
print("Hello " + name)
greet("Sam")function ticketPrice(tickets) // function: returns a value
return tickets * 12.50
endfunction
total = ticketPrice(3)
print(total)
procedure greet(name) // procedure: does a task, returns nothing
print("Hello " + name)
endprocedure
greet("Sam")Local and global variables
global keyword, updated) from anywhere in the program, including inside sub-programs.global keyword explicitly declares or modifies a global variable. Arrays can also be passed into and returned from sub-programs, just like any other data type.def density(mass, volume):
d = mass / volume # d is local, only exists in this function
return d
user_mass = float(input("Enter mass: ")) # global
user_volume = float(input("Enter volume: "))
user_density = density(user_mass, user_volume)
# print(d) here would cause an error, d does not exist outside the function
def double_values(values): # an array can be passed into a sub-program...
for i in range(len(values)):
values[i] = values[i] * 2
return values # ...and returned, just like any other data type
numbers = [1, 2, 3]
numbers = double_values(numbers)function density(mass, volume)
d = mass / volume // d is local, only exists in this function
return d
endfunction
global userMass = real(input("Enter mass: "))
userVolume = real(input("Enter volume: "))
userDensity = density(userMass, userVolume)
// print(d) here would cause an error, d does not exist outside the function
function doubleValues(values, size) // an array can be passed into a sub-program...
for i = 0 to size - 1
values[i] = values[i] * 2
next i
return values // ...and returned, just like any other data type
endfunction
array numbers = [1, 2, 3]
numbers = doubleValues(numbers, 3)Random number generation
random(1, 6) generates a random integer between 1 and 6 inclusive (like a dice roll). If the value will be used more than once, store it in a variable rather than generating it again.import random
roll = random.randint(1, 6)
print(roll)roll = random(1, 6)
print(roll)Exam Phrasing: Use These Exact Phrases
- ✓An array is a fixed-length (static) data structure, indexed from 0
- ✓A record groups related fields together as one unit, similar to a row in a table
- ✓A function returns a value; a procedure does not
- ✓A local variable only exists inside the sub-program it was created in; a global variable can be used anywhere
- ✓SQL field names are separated by commas, and string values must be enclosed in quotation marks
- 💡Remember arrays are fixed-length/static, this is a frequently tested fact, especially when comparing to Python lists.
- 💡In SQL, use WHERE (not IF) to filter results, separate multiple fields with commas (not AND), and put string values in quotation marks.
- 💡A record is best described as an entire row of related data, e.g. [1, "Platinum", "Saturday", 0.5], not just a single value.
- 💡When defining a function, pass data in through its parameters, never ask for separate input inside it, and always return the result rather than printing it.
- 💡When calling a function, actually use what it returns (e.g. assign it to a variable), don't redefine the function or recalculate the answer separately.
- 💡Arrays can be passed into a sub-program as a parameter, and returned from one, exactly like any other data type.
Wrong:
SELECT Model FROM Cars IF Sold = "no"
Right:
SELECT Model FROM Cars WHERE Sold = False
Why it matters: SQL uses WHERE to filter results, not IF, and field/table names must not contain spaces.
Wrong:
A function asks for its own input instead of using its parameters
Right:
A function uses the values passed into it via its parameters
Why it matters: Asking for separate input overwrites the parameter and ignores the data the caller intended to pass in, losing marks.
Wrong:
A function prints its result instead of returning it
Right:
A function uses return to give back its result, which the caller can then use
Why it matters: Printing inside a function does not make the result available to the rest of the program, only returning it does.
Wrong:
Using a comma to join two strings together, e.g. message = word1, word2
Right:
Concatenate with +, e.g. message = word1 + word2
Why it matters: OCR examiners flagged this specifically. In most languages, and especially Python, a comma prints two separate items or passes two arguments, it does not concatenate them into one value. Examiners accept +, &, . or a sensible function such as concat(), but never a comma.
Wrong:
Writing for x in list, then trying to use list[x] later in the code
Right:
In that style of loop x is the item itself, not its index, so use x directly (or loop over the indexes instead if you need positions)
Why it matters: OCR examiners flagged this exact mistake. Treating the loop variable as an index when it is actually the value makes the rest of the code wrong.
Wrong:
An array can grow in size when new items are added
Right:
An array is fixed-length (static), its size cannot change once declared
Why it matters: This is a specifically, repeatedly examined fact, confused with Python's dynamic lists.
Question:
Define a function called ticketPrice that takes the number of tickets as a parameter, calculates the total cost (each ticket costs 12.50), and returns the result. Then show how the function would be called to calculate the price of 3 tickets, storing the result in a variable called total. [4]
def ticket_price(tickets):
return tickets * 12.50
total = ticket_price(3)
print(total)function ticketPrice(tickets)
return tickets * 12.50
endfunction
total = ticketPrice(3)
print(total)💡 Attempt this before revealing the answer, practice makes perfect!
Model Answer:
The function is defined with one parameter, tickets. Inside the function, the price is calculated by multiplying tickets by 12.50, and this value is returned using the return keyword. The function is then called with the argument 3, and the returned value is stored in the variable total using assignment.
Mark Scheme:
- 1Function correctly defined with a parameter named tickets (not asking for separate input)
- 2Correct calculation: tickets multiplied by 12.50
- 3Result correctly returned using return, not printed
- 4Function correctly called with 3, and the result assigned to the variable total
Tap a card to flip it. Use the arrow keys to move and space to flip.
Exam-style questions. Have a go, then reveal the mark scheme to check your answer.
1.Give an example of a record from a table storing book loans, with fields for BookID, Title, and OnLoan.
[1]2.Explain why an array is described as a "static" or "fixed-length" data structure.
[2]3.A candidate defines a function to calculate the area of a rectangle, but instead of using the given parameters width and height, the function asks the user to input them again. Explain why this is incorrect.
[2]4.Write an SQL query to select the Title and Author fields from a table called Books, where the Genre field is "Fantasy".
[3]5.Define a function called rectangleArea that takes width and height as parameters and returns the area. Show how it would be called to store the area of a rectangle with width 5 and height 3 in a variable called result.
[4]def rectangle_area(width, height):
return width * height
result = rectangle_area(5, 3)function rectangleArea(width, height)
return width * height
endfunction
result = rectangleArea(5, 3)6.A program stores the seating plan for a classroom of 5 rows with 6 seats in each row. Explain why a 2D array is a suitable structure, and describe how a specific seat would be accessed.
[6]The examiners' reports are the most useful and least read of the three: they say what candidates actually got wrong each year. All files are hosted by OCR.
Past-paper questions grouped by topic
The same OCR questions, sorted by topic rather than by year (via Physics & Maths Tutor).
Only a small percentage of candidates could give a correct example of a record, such as an entire row of a database table (e.g. [1, "Platinum", "Saturday", 0.5]). This was the lowest scoring question on the entire paper, despite records being an explicitly named, required part of the specification (2.2.3).
In an SQL question, most candidates identified that the table name and filtering keyword needed correcting (IF should be WHERE), but far fewer replaced an incorrect AND between field names with a comma, or noticed missing quotation marks around a string value. SQL is case-insensitive so candidate answers do not need capitals, but field/table names must never contain spaces.
When defining and using functions, a common misconception was either omitting a parameter in the function definition, or overwriting/ignoring a given parameter by asking for separate input inside the function instead. Another common misconception was printing the calculated result instead of returning it. When later asked to use the function, many candidates redefined the function again or calculated the result a different way, instead of calling the function and using its returned value.
In a question involving iterating through an array to implement a linear search, most candidates correctly identified the loop bounds and the value to return if the item was found, but fewer correctly used the loop's counter variable as the index into the array, this is a more advanced skill combining arrays with count-controlled loops that centres are encouraged to practise together.