2.2.3 Additional programming techniques · Paper 2
More programming: strings, files, arrays, SQL and sub programs
Each section has pictures and things to try, then its key points and key words. Exam practice is at the end of the page.
You need to know
- Basic string manipulation, including joining (concatenation) and slicing
- File handling: open, read, write, close
- Records, and using SQL (SELECT, FROM, WHERE) to search data
- 1D and 2D arrays (fixed length), and using 2D arrays like database tables
- Functions and procedures, local and global variables, passing and returning values
- Random number generation
You don't need to know
- OCR doesn't rule anything out here.
Strings
A string is a row of characters. Each character has an index (position), starting at 0.
- Concatenation joins strings with +: "Computer" + " Science".
- Slicing (a substring) takes part of a string. OCR writes word.substring(start, length). Python writes word[start:end], where end is not included.
Try it
Type a word, then change the start and length to take a slice.
Key points
Working with strings
Before this: 2.2.2Data types
- Concatenation joins strings with +: "Comp" + "uter" "Computer".
- Characters are numbered from 0.
- Length: word.length (Python len(word)).
- Slicing: word.substring(start, howMany), word.left(n), word.right(n).
- Case: word.upper and word.lower.
| word = "Computer" | OCR reference language | Python | Result |
|---|---|---|---|
| Length | word.length | len(word) | 8 |
| First 4 | word.substring(0, 4) | word[0:4] | Comp |
| Left 3 | word.left(3) | word[:3] | Com |
| Right 3 | word.right(3) | word[-3:] | ter |
| Capitals | word.upper | word.upper() | COMPUTER |
Key words
Say what each one means, then tap to check.
Files
Programs save data in files so it is still there after the program ends.
OCR Exam Reference Language
myFile = open("scores.txt") line = myFile.readLine() myFile.writeLine("Sam,12") myFile.close()
Python
myFile = open("scores.txt", "r") line = myFile.readline() myFile.close() myFile = open("scores.txt", "a") myFile.write("Sam,12\n") myFile.close()
Python opens a file once to read ("r") and again to add to it ("a").
OCR also uses newFile("name.txt") to make a new file, and myFile.endOfFile() to check when there is nothing left to read.
Key points
Reading and writing files
Before this: Working with strings
- Files keep data after the program closes. Variables are lost when it ends.
- Three steps: open the file, read or write, then close it.
- readLine() reads one line. writeLine() writes one line.
- endOfFile() tells you when there's nothing left to read.
- Always close the file, so the data is saved and other programs can use it.
Writing (Python)
f = open("scores.txt", "a") f.write("Ali,12\n") f.close()
Writing (OCR reference language)
myFile = open("scores.txt") myFile.writeLine("Ali,12") myFile.close()
Key words
Say what each one means, then tap to check.
Arrays and records
An array stores many values of the same type under one name. Each has an index, starting at 0. A 2D array is like a table with rows and columns.
scores = [12, 18, 9] # scores[1] is 18 grid = [[1, 2, 3], [4, 5, 6]] # grid[1][2] is 6 (row 1, column 2)
A record groups related data of different types, like one row in a database: a student's name, age and form.
OCR writes a 2D array index with a comma, grid[1,2]. Python uses two sets of brackets, grid[1][2].
Try it
Tap boxes to see their index. Then press "Give me a challenge".
Key points
Records
Before this: 2.2.2Data types
- A record stores all the data about one thing, like one row in a table.
- Each piece of data in a record is a field, like a column in a table.
- Fields can be different data types, e.g. a name (string) and an age (integer).
- A table is a collection of records with the same fields.
- Records can be searched with SQL.
| PetID | Name | Type | Age |
|---|---|---|---|
| 1 | Bella | Dog | 4 |
| 2 | Milo | Cat | 2 |
| 3 | Coco | Rabbit | 1 |
| 4 | Max | Dog | 7 |
| 5 | Luna | Cat | 5 |
Arrays
Before this: 2.2.1Count-controlled loops (for)
- An array stores many values under one name, usually all the same data type.
- Each value has an index. The first index is 0.
- scores[2] means the third item.
- In the OCR reference language arrays have a fixed size: array scores[5].
- Use a for loop to go through every item.
2D arrays
Before this: Arrays
- A 2D array is like a table or grid, with rows and columns.
- You need two indexes to find an item: scores[1, 2]. In Python, scores[1][2].
- Both indexes start at 0. The question will say which index is the row and which is the column.
- Use a loop inside a loop (nesting) to visit every item.
| Test 0 | Test 1 | Test 2 | Test 3 | |
|---|---|---|---|---|
| Student 0 | 12 | 15 | 9 | 18 |
| Student 1 | 7 | 14 | 20 | 11 |
| Student 2 | 16 | 10 | 13 | 19 |
scores[1, 2] is student 1, test 2: the value 20.
Key words
Say what each one means, then tap to check.
SQL
SELECT name, form FROM Students WHERE age > 14
SELECT which fields, FROM which table, WHERE the condition. SELECT * means every field. Text values go in quote marks, e.g. WHERE form = "10B".
Try it
Build a query. Can you show just the names of everyone in 10B? Everyone in Red house, with every field?
Key points
Searching data with SQL
Before this: Records
- SQL is used to search a database.
- SELECT which fields to show. FROM which table. WHERE the condition.
- SELECT * shows every field.
- Join conditions with AND and OR.
- LIKE with % finds patterns: WHERE Name LIKE "M%" finds names starting with M.
Example table: Pets
| PetID | Name | Type | Age |
|---|---|---|---|
| 1 | Bella | Dog | 4 |
| 2 | Milo | Cat | 2 |
| 3 | Coco | Rabbit | 1 |
| 4 | Max | Dog | 7 |
| 5 | Luna | Cat | 5 |
SELECT Name, Age FROM Pets WHERE Type = "Cat" Milo 2, Luna 5
Key words
Say what each one means, then tap to check.
Sub programs
| Procedure | Function |
|---|---|
| A named block of code that does a task | A named block of code that does a task and returns a value |
| def greet(name): print("Hi " + name) | def double(n): return n * 2 |
- Local variable: only exists inside its sub program.
- Global variable: can be used anywhere in the program.
- Sub programs avoid repeating code and make programs easier to test and read.
Key points
Procedures
Before this: 2.2.1Sequence
- A procedure is a named block of code that does a task. You run it by calling its name.
- Values can be passed in using parameters.
- A procedure doesn't return a value. (A function does.)
- Sub programs mean you write code once and reuse it, which makes programs shorter and easier to test.
Python
def greet(name): print("Hello " + name) greet("Sam")
OCR reference language
procedure greet(name) print("Hello " + name) endprocedure greet("Sam")
Functions
Before this: Procedures
- A function is a sub program that returns a value to the code that called it.
- Use return to send the value back.
- The returned value is usually stored in a variable or output: a = area(3, 4).
- input(), len() and int() are built-in functions.
Python
def area(w, h): return w * h a = area(3, 4) print(a)
OCR reference language
function area(w, h) return w * h endfunction a = area(3, 4) print(a)
Local and global variables
Before this: Functions
- A local variable is made inside a sub program. It only exists while that sub program runs.
- A global variable is made in the main program and can be used anywhere.
- OCR reference language: global score = 0.
- Local variables are safer: other parts of the program can't change them by mistake, and the same name can be reused in different sub programs.
Key words
Say what each one means, then tap to check.
Random numbers
random(1, 6) in OCR, or random.randint(1, 6) in Python, gives a random whole number from 1 to 6. Both ends are included. Games, quizzes and simulations use random numbers.
Try it
Roll once, then roll 600 times. Does every number come up?
Key points
Random numbers
Before this: 2.2.1Arithmetic operators
- Programs can make random numbers for games, quizzes and simulations.
- OCR reference language: random(1, 6) gives a whole number from 1 to 6, like a dice.
- Python: import random then random.randint(1, 6). Both ends are included.
- Each time the program runs, the number will probably be different.
Python
import random roll = random.randint(1, 6) print(roll)
OCR reference language
roll = random(1, 6) print(roll)
Key words
Say what each one means, then tap to check.
Exam practice
31 questions in the style of the OCR exam, 77 marks in total. Try each one, then check the mark scheme.
Strings
print(name.substring(0, 3))
print(name.length)
Hint
Characters are numbered from 0. How many characters does substring(0, 3) take? Then count every letter in Jessica.
State means give a short, clear answer. You don't need to explain it.
2 marks: make 2 separate points.
Show mark scheme
- Jes
- 7
Don't accept: Ess for the first line. The first character is at index 0, so it is J.
1 mark for each.
Write an algorithm that inputs a first name and surname and outputs the username.
Hint
Use left(3) on the first name and right(3) on the surname, then join them with +.
Write means write the code or algorithm. OCR Exam Reference Language or Python both get marks.
3 marks: each part that works earns marks, even if the whole thing isn't perfect.
Show mark scheme
- Input both names.
- Take the first 3 letters of the first name and last 3 of the surname.
- Concatenate them and output.
Also accept: first[:3] + last[-3:] (Python).
Example answer
first = input("First name") last = input("Surname") user = first.left(3) + last.right(3) print(user)
1 mark for each point. Python is fine too.
Files
Hint
Think about the data being saved, and about other programs that might want the file.
Explain means say what happens and why. Words like “because” and “so” help.
2 marks: aim for 2 things said, such as a point and then the reason for it.
Show mark scheme
- Makes sure the data is saved / written.
- Frees the file so other programs / users can use it.
1 mark for each.
Hint
Open it, loop until the end of the file reading one line each time, then close it.
Write means write the code or algorithm. OCR Exam Reference Language or Python both get marks.
4 marks: each part that works earns marks, even if the whole thing isn't perfect.
Show mark scheme
- Open names.txt.
- Loop until end of file.
- Read a line and output it inside the loop.
- Close the file.
Also accept: Python: for line in file: print(line)
Don't accept: Reading only one line. A loop is needed to read every line.
Example answer
myFile = open("names.txt") while NOT myFile.endOfFile() print(myFile.readLine()) endwhile myFile.close()
1 mark for each point. Python is fine too.
Hint
What happens to the values in variables when the program closes?
Give means give a short, clear answer. You don't need to explain it.
1 mark: one answer is enough.
Show mark scheme
- The scores are kept after the program closes / when the computer is turned off.
Arrays and records
Hint
Think of a table. Which one is a column, and which one is a row?
State means give a short, clear answer. You don't need to explain it.
2 marks: make 2 separate points.
Show mark scheme
- A field is one item of data / a column.
- A record is all the data about one thing / a row.
1 mark for each.
| PetID | Name | Type | Age |
|---|---|---|---|
| 1 | Bella | Dog | 4 |
| 2 | Milo | Cat | 2 |
| 3 | Coco | Rabbit | 1 |
| 4 | Max | Dog | 7 |
| 5 | Luna | Cat | 5 |
Hint
Each row is a record and each column is a field. Don't count the header row.
State means give a short, clear answer. You don't need to explain it.
2 marks: make 2 separate points.
Show mark scheme
- 5 records
- 4 fields
Don't accept: 6 records. The header row is not a record.
1 mark for each.
Hint
The first item is at index 0, so count from 0.
State means give a short, clear answer. You don't need to explain it.
1 mark: one answer is enough.
Show mark scheme
- "blue"
Don't accept: "green". That is colours[1].
Hint
What should the total start at? Which indexes does a 10-item array use? Should you output inside the loop or after it?
Write means write the code or algorithm. OCR Exam Reference Language or Python both get marks.
4 marks: each part that works earns marks, even if the whole thing isn't perfect.
Show mark scheme
- Total set to 0.
- Loop through all 10 items (index 0 to 9).
- Add each item to the total.
- Output the total after the loop.
Also accept: for i = 0 to scores.length - 1
Don't accept: for i = 1 to 10. The indexes go from 0 to 9, so scores[10] doesn't exist.
Example answer
total = 0 for i = 0 to 9 total = total + scores[i] next i print(total)
1 mark for each point. Python is fine too.
Hint
Imagine writing a program with 1,000 separate variables instead of one array.
Give means give a short, clear answer. You don't need to explain it.
2 marks: make 2 separate points.
Show mark scheme
- Less code to write.
- Can use a loop to process every item.
- Easier to find / sort / search the data.
- Data is grouped under one name.
1 mark for each, up to 2.
| Test 0 | Test 1 | Test 2 | Test 3 | |
|---|---|---|---|---|
| Student 0 | 12 | 15 | 9 | 18 |
| Student 1 | 7 | 14 | 20 | 11 |
| Student 2 | 16 | 10 | 13 | 19 |
Hint
The first number picks the row (student). The second picks the column (test). Both start at 0.
State means give a short, clear answer. You don't need to explain it.
2 marks: make 2 separate points.
Show mark scheme
- 20
- 16
1 mark for each.
Hint
Student 2 is the third row. Keep the first index as 2 and loop the second index from 0 to 3.
Write means write the code or algorithm. OCR Exam Reference Language or Python both get marks.
3 marks: each part that works earns marks, even if the whole thing isn't perfect.
Show mark scheme
- Loop through tests 0 to 3.
- Add scores[2, test] to a total.
- Output the total (58).
Also accept: Adding the four items directly, e.g. scores[2,0] + scores[2,1] + scores[2,2] + scores[2,3].
Example answer
total = 0 for t = 0 to 3 total = total + scores[2, t] next t print(total)
1 mark for each point. Python is fine too.
SQL
| PetID | Name | Type | Age |
|---|---|---|---|
| 1 | Bella | Dog | 4 |
| 2 | Milo | Cat | 2 |
| 3 | Coco | Rabbit | 1 |
| 4 | Max | Dog | 7 |
| 5 | Luna | Cat | 5 |
Hint
Three lines: SELECT the field you want, FROM the table, WHERE the condition. Text goes in quote marks.
Write means write the SQL. Put SELECT, FROM and WHERE each on its own line.
3 marks: usually one mark for each correct line.
Show mark scheme
- SELECT Name
- FROM Pets
- WHERE Type = "Dog"
Also accept: Single quotes, e.g. Type = 'Dog'.
Also accept: Keywords in lower case.
Don't accept: SELECT * for the first line. It shows every field, not just the names.
Example answer
SELECT Name FROM Pets WHERE Type = "Dog"
1 mark for each line.
SELECT Name, Age FROM Pets WHERE Age > 4
Hint
Check each pet's age. Is it more than 4? Then show only the Name and Age fields.
State means give a short, clear answer. You don't need to explain it.
2 marks: make 2 separate points.
Show mark scheme
- Max, 7
- Luna, 5
Don't accept: Bella. Her age is 4, which is not more than 4.
1 mark for each.
Hint
The WHERE line needs two conditions joined with AND.
Write means write the SQL. Put SELECT, FROM and WHERE each on its own line.
3 marks: usually one mark for each correct line.
Show mark scheme
- SELECT Name, Type
- FROM Pets
- WHERE Type = "Cat" AND Age > 3
Don't accept: Two WHERE lines, e.g. WHERE Type = "Cat" WHERE Age > 3. Join the conditions with AND.
Don't accept: Age >= 3. A cat aged 3 is not older than 3.
Example answer
SELECT Name, Type FROM Pets WHERE Type = "Cat" AND Age > 3
1 mark for each line.
Sub programs
Hint
Start with procedure stars(n). Inside it, loop n times and print a * each time.
Write means write the code or algorithm. OCR Exam Reference Language or Python both get marks.
3 marks: each part that works earns marks, even if the whole thing isn't perfect.
Show mark scheme
- procedure stars(n) … endprocedure
- Loop n times.
- Output * inside the loop.
Also accept: Python: def stars(n): with a for loop inside.
Don't accept: A procedure with no parameter. The number must be passed in.
Example answer
procedure stars(n) for i = 1 to n print("*") next i endprocedure
1 mark for each point. Python is fine too.
Hint
Think about reusing code, testing, and sharing work in a team.
Give means give a short, clear answer. You don't need to explain it.
2 marks: make 2 separate points.
Show mark scheme
- Code can be reused / no need to repeat code.
- Easier to test each part.
- Easier to read / maintain.
- Different programmers can work on different sub programs.
1 mark for each, up to 2.
Hint
One of them sends a value back to where it was called.
State means give a short, clear answer. You don't need to explain it.
1 mark: one answer is enough.
Show mark scheme
- A function returns a value; a procedure doesn't.
Hint
It needs a parameter for the Celsius value, the formula, and return.
Write means write the code or algorithm. OCR Exam Reference Language or Python both get marks.
3 marks: each part that works earns marks, even if the whole thing isn't perfect.
Show mark scheme
- Function with one parameter.
- Correct calculation.
- Returns the result.
Also accept: c * 1.8 + 32.
Example answer
function toFahrenheit(c) return c * 9 / 5 + 32 endfunction
1 mark for each point. Python is fine too.
function double(n) return n * 2 endfunction print(double(double(3)))
Hint
Work from the inside out. What is double(3)? Then double that.
State means give a short, clear answer. You don't need to explain it.
1 mark: one answer is enough.
Show mark scheme
- 12
Don't accept: 6. The function is called twice.
Hint
Where is each one made, and where can it be used?
Explain means say what happens and why. Words like “because” and “so” help.
2 marks: aim for 2 things said, such as a point and then the reason for it.
Show mark scheme
- A local variable can only be used in the sub program it was made in.
- A global variable can be used anywhere in the program.
Also accept: A local variable only exists while its sub program is running.
1 mark for each.
Hint
What could go wrong if every part of a big program could change the same variable?
Give means give a short, clear answer. You don't need to explain it.
2 marks: make 2 separate points.
Show mark scheme
- Can't be changed by mistake by other parts of the program.
- The same name can be used in different sub programs.
- Memory is freed when the sub program ends.
- Sub programs are easier to reuse / test on their own.
1 mark for each, up to 2.
Random numbers
Hint
Two dice means two random numbers from 1 to 6. Add them, then output.
Write means write the code or algorithm. OCR Exam Reference Language or Python both get marks.
3 marks: each part that works earns marks, even if the whole thing isn't perfect.
Show mark scheme
- Two random numbers from 1 to 6.
- Add them together.
- Output the total.
Don't accept: random(2, 12). Totals from two dice are not all equally likely, e.g. 7 comes up more than 2.
Example answer
d1 = random(1, 6) d2 = random(1, 6) print(d1 + d2)
1 mark for each point. Python is fine too.
Hint
Break it into steps: pick the number, then a loop that asks for a guess, adds 1 to a count, and says Higher or Lower. When should the loop stop?
Write means write the code or algorithm. OCR Exam Reference Language or Python both get marks.
5 marks: each part that works earns marks, even if the whole thing isn't perfect.
Show mark scheme
- Random number from 1 to 100.
- Loop until the guess is correct.
- Input a guess (as an integer) inside the loop.
- Output Higher / Lower correctly.
- Count the guesses and output the count at the end.
Also accept: A while loop that repeats while guess != target.
Don't accept: Picking a new random number inside the loop. The number must stay the same until it is guessed.
Example answer
target = random(1, 100) guesses = 0 do guess = int(input("Guess")) guesses = guesses + 1 if guess < target then print("Higher") elseif guess > target then print("Lower") endif until guess == target print("Got it in " + str(guesses))
1 mark for each point. Python is fine too.
Mixed questions on the whole page
State the output of each line.
- print(len(word))
- print(word[0:3])
- print(word.upper())
Hint
Count every letter for the length. The slice starts at index 0 and stops before index 3.
State means give a short, clear answer. You don't need to explain it.
3 marks: make 3 separate points.
Show mark scheme
- a) 8
- b) Com
- c) COMPUTER
Don't accept: b) "Comp". [0:3] stops before position 3, so only 3 characters are shown.
1 mark for each.
Hint
SELECT the two fields, FROM the table, WHERE the condition. "Over 50" means > 50.
Write means write the SQL. Put SELECT, FROM and WHERE each on its own line.
3 marks: usually one mark for each correct line.
Show mark scheme
- SELECT name, score
- FROM Results
- WHERE score > 50
Don't accept: WHERE score >= 50. That includes a score of exactly 50.
Example answer
SELECT name, score FROM Results WHERE score > 50
1 mark for each line.
def check(age): return age >= 18
Hint
Look for the word return. What does a function do that a procedure doesn't?
State means give a short, clear answer. You don't need to explain it.
2 marks: make 2 separate points.
Show mark scheme
- Function.
- It returns a value (True or False).
1 mark for function, 1 mark for the reason.
Hint
What would happen if the same lines were copied five times, and then you found a mistake in them?
Explain means say what happens and why. Words like “because” and “so” help.
2 marks: aim for 2 things said, such as a point and then the reason for it.
Show mark scheme
- The code is written once and called five times, so there is less code / no repeated code.
- If there is a mistake it only needs fixing and testing in one place.
1 mark for each point.
Hint
Keep the biggest value so far in a variable. Start it at temps[0], then check every other item against it.
Write means write the code or algorithm. OCR Exam Reference Language or Python both get marks.
4 marks: each part that works earns marks, even if the whole thing isn't perfect.
Show mark scheme
- Sets highest to the first item, temps[0].
- Loops through the rest of the array.
- Compares each item with highest and replaces highest if it is bigger.
- Outputs highest after the loop.
Also accept: Setting highest to a very low number first, e.g. -100, instead of temps[0].
Also accept: Looping through all 7 items (0 to 6).
Example answer
highest = temps[0] for i = 1 to 6 if temps[i] > highest then highest = temps[i] endif next i print(highest)
1 mark for each point. Python is fine too. Just using max(temps) gets 1 mark, as it does not show the algorithm.
procedure addOne() count = 1 endprocedure count = 5 addOne() print(count)
Hint
Is the count inside the procedure the same variable as the count in the main program? Where was each one made?
State means give a short, clear answer. You don't need to explain it.
2 marks: make 2 separate points.
Show mark scheme
- 5
- The count inside the procedure is a local variable, so changing it does not change the count in the main program.
Don't accept: 1. The procedure only changes its own local count.
1 mark for the output, 1 mark for the reason.
Hint
Store the random number in a variable first, so you can check it and output it.
Write means write the code or algorithm. OCR Exam Reference Language or Python both get marks.
3 marks: each part that works earns marks, even if the whole thing isn't perfect.
Show mark scheme
- A random integer from 1 to 10, stored in a variable.
- An if that checks whether it equals 7…
- …and outputs Lucky! or the number.
Also accept: random.randint(1, 10) in Python.
Don't accept: Comparing with "7" in quotes. The random number is an integer, so it will never equal the string "7".
Example answer
num = random(1, 10) if num == 7 then print("Lucky!") else print(num) endif
1 mark for each point. Python is fine too.