2.2.1 Programming fundamentals
Every program is built from a small set of ideas: storing values, doing calculations, making decisions and repeating steps. This topic covers all of them. All code is in the OCR Exam Reference Language, which is the style used in the exam.
Variables, constants and assignment
score = 0
name = "Louise"
score = score + 10
const vat = 0.2
The line score = score + 10 works out the right-hand side first (0 + 10), then stores the answer back in score. The old value is replaced.
Use a constant for a value that never changes, such as a tax rate. If the value ever needs changing, you change it in one place only. It also makes the code easier to read, because vat is clearer than 0.2.
Inputs and outputs
An input is data that goes into the program, for example from the keyboard. An output is data that comes out of the program, for example text on the screen.
myName = input("Please enter a name")
print("My name is " + myName)
The text inside input(...) is the prompt shown to the user. Whatever the user types is stored in the variable on the left. Input always arrives as a string, so numbers must be cast with int() or float() before you calculate with them. Casting is explained in 2.2.2.
age = int(input("Enter your age"))
print(age + 1)
The three programming constructs
Every program is made from three building blocks.
| Construct | What it does |
|---|---|
| Sequence | Runs the lines one after another, in order |
| Selection | Chooses which lines to run, depending on a condition |
| Iteration | Repeats lines of code |
width = 4
height = 3
area = width * height
print(area)
Order matters. If the print line came first, area would not have a value yet.
Arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | Add | 6 + 4 | 10 |
| - | Subtract | 6 - 4 | 2 |
| * | Multiply | 6 * 4 | 24 |
| / | Divide (gives a real number) | 17 / 5 | 3.4 |
| DIV | Whole-number part of a division | 17 DIV 5 | 3 |
| MOD | Remainder of a division | 17 MOD 5 | 2 |
| ^ | To the power of (exponent) | 2 ^ 3 | 8 |
Order of operations
Brackets are worked out first. Then ^. Then *, /, DIV and MOD. Then + and -.
- 2 + 3 * 4: multiply first, so 3 * 4 = 12, then 2 + 12 = 14.
- (2 + 3) * 4: the brackets come first, so 5 * 4 = 20.
- 2 ^ 3 + 1: the power comes first, so 8 + 1 = 9.
- 7 ^ 2 is 7 * 7 = 49.
Uses of DIV and MOD
length = 125
hours = length DIV 60
minutes = length MOD 60
print(hours) // 2
print(minutes) // 5
125 divided by 60 is 2 remainder 5, so the film is 2 hours 5 minutes.
MOD is also used to test for even numbers. A number is even when dividing by 2 leaves no remainder.
if number MOD 2 == 0 then
print("Even")
endif
For example 14 MOD 2 is 0, so 14 is even. 15 MOD 2 is 1, so 15 is odd.
Using a constant in a calculation
const vat = 0.2
price = 50
total = price + price * vat
print(total) // 60
Multiplication happens before addition, so price * vat is 10, and 50 + 10 is 60.
Comparison operators
A comparison gives the answer True or False. These are used in conditions.
| Operator | Meaning | Example | Result |
|---|---|---|---|
| == | Equal to | 5 == 5 | True |
| != | Not equal to | 5 != 5 | False |
| < | Less than | 3 < 5 | True |
| <= | Less than or equal to | 5 <= 5 | True |
| > | Greater than | 3 > 5 | False |
| >= | Greater than or equal to | 5 >= 6 | False |
Boolean operators
A condition can be built from smaller conditions using AND, OR and NOT.
| Operator | Meaning |
|---|---|
| AND | True only when both conditions are True |
| OR | True when at least one condition is True |
| NOT | Turns True into False and False into True |
Suppose score is 70 and lives is 0.
| Condition | Working | Result |
|---|---|---|
| score > 50 AND lives > 0 | True AND False | False |
| score > 50 OR lives > 0 | True OR False | True |
| NOT (lives > 0) | NOT False | True |
AND is often used to check a range. The test age >= 13 AND age <= 17 is True only for ages from 13 to 17.
Selection
if, elseif and else
mark = int(input("Enter mark"))
if mark >= 80 then
print("Distinction")
elseif mark >= 60 then
print("Merit")
else
print("Pass")
endif
The program checks the conditions from the top. The first one that is True is run, then the program skips to endif. The else part runs only if none of the conditions were True.
| mark | Check 1 (mark >= 80) | Check 2 (mark >= 60) | Output |
|---|---|---|---|
| 80 | True | not checked | Distinction |
| 65 | False | True | Merit |
| 59 | False | False | Pass |
Notice that 80 gives Distinction because >= includes the value 80 itself.
switch
A switch statement chooses between many fixed values of one variable. It is a tidy alternative to a long chain of elseif lines.
switch day :
case "Sat":
print("Saturday")
case "Sun":
print("Sunday")
default:
print("Weekday")
endswitch
If day holds "Sun", the program prints Sunday. If day holds "Tue", no case matches, so the default part runs and it prints Weekday.
Iteration
There are two kinds. A count-controlled loop repeats a set number of times. A condition-controlled loop repeats until a condition changes.
Count-controlled: for loops
total = 0
for i = 1 to 4
total = total + i
next i
print(total) // 10
The loop variable i takes each value from 1 to 4, including both ends. Here is a trace table.
| i | total after the pass |
|---|---|
| 1 | 1 |
| 2 | 3 |
| 3 | 6 |
| 4 | 10 |
Use step to count in jumps, including backwards.
for i = 2 to 10 step 2
print(i) // 2, 4, 6, 8, 10
next i
for i = 10 to 0 step -3
print(i) // 10, 7, 4, 1
next i
In the second loop the next value would be -2, which is past 0, so the loop stops after 1.
Condition-controlled: while loops
A while loop checks its condition before each pass. If the condition is False at the start, the loop never runs.
n = 1
while n < 50
n = n * 3
endwhile
print(n) // 81
| n at the start of the pass | n < 50? | n after the pass |
|---|---|---|
| 1 | True | 3 |
| 3 | True | 9 |
| 9 | True | 27 |
| 27 | True | 81 |
| 81 | False | loop stops |
Condition-controlled: do-until loops
A do-until loop checks its condition after each pass, and it stops when the condition is True. So it always runs at least once.
do
guess = int(input("Guess the number"))
until guess == 7
| while loop | do-until loop |
|---|---|
| Condition checked at the start | Condition checked at the end |
| Repeats while the condition is True | Repeats until the condition is True |
| May run zero times | Always runs at least once |
Putting it together
attempts = 1
password = input("Enter password")
while password != "tiger"
password = input("Enter password")
attempts = attempts + 1
endwhile
print(attempts)
If the user types "cat", "dog" then "tiger", attempts goes 1, 2, 3 and the program prints 3. The first input is outside the loop so the condition has a value to check.
Other topics you may use in programs, such as string handling, arrays, files and sub programs, are covered in 2.2.3.
Exam technique
- •State or give: write the value or the answer only, such as the number printed.
- •Complete: fill the gaps in the code with the correct keywords, such as while, endwhile or elseif.
- •Trace: work through the code line by line, writing down each variable's value. A trace table helps. Check carefully whether a loop includes its last value.
- •Correct or identify the error: say the line number, then what is wrong, then what it should be.
- •Write: use the reference language, or a high-level language you have learned. Do not use plain English. Give variables a value before using them, use == in conditions, and finish every if with endif, every while with endwhile and every for with next.
- •Explain: give a point and a reason, for example "a constant is used so the value only has to be changed in one place".