A levels Computer Science · Programming and data
Programming fundamentals
1Variables, constants and assignment
A variable is a named location in memory whose value can change while the program runs. A constant is named once and never changes, for example VAT_RATE = 0.2.
- Assignment gives a variable a value:
total = total + price. - Use meaningful identifiers (
score, nots) so the code explains itself. - Constants make code easier to update (change one line) and stop a value being changed by mistake.
VAT_RATE = 0.2
price = 50
total = price * (1 + VAT_RATE)
print(total) # 60.0
The basic arithmetic operators are +, −, *, / (real division), // (integer division, called DIV) and % (remainder, called MOD). For example, 17 // 5 = 3 and 17 % 5 = 2.
Check yourself
What is 23 MOD 4?
Show the answer
3
23 = 5 × 4 + 3.
2Selection and iteration
Every program can be built from three structures: sequence, selection and iteration.
mark = int(input("Mark: "))
if mark >= 70:
grade = "A"
elif mark >= 50:
grade = "C"
else:
grade = "U"
| Loop | Type | When to use |
|---|---|---|
| for | count-controlled (definite) | the number of repeats is known |
| while | condition-controlled, checked at the start | may run zero times |
| repeat ... until | condition-controlled, checked at the end | always runs at least once |
Validation with a while loop keeps asking until the input is acceptable:
age = int(input("Age: "))
while age < 0 or age > 120:
age = int(input("Try again: "))
Check yourself
Which loop always runs its body at least once?
Show the answer
repeat ... until (a post-condition loop)
Checked at the end.
3Subroutines, parameters and scope
A subroutine is a named block of code that performs a task. A function returns a value; a procedure does not.
def area(width, height): # parameters
return width * heightroom = area(4, 5) # arguments 4 and 5; room = 20
- Parameters are the names in the definition; arguments are the values passed in.
- Parameters can be passed by value (a copy, so the original cannot change) or by reference (the address, so the subroutine can change the original).
- A local variable exists only inside its subroutine. A global variable can be used anywhere, but makes code harder to test and debug.
Benefits of subroutines: code is reused rather than repeated, each part can be tested on its own, and teams can work on different subroutines at once.
Check yourself
What is the difference between a function and a procedure?
Show the answer
A function returns a value; a procedure does not
Return value.
4Recursion
A recursive subroutine calls itself. It needs a base case that stops the recursion, and each call must move closer to that base case.
def factorial(n):
if n == 1: # base case
return 1
return n * factorial(n - 1)
factorial(4): each call waits on the call stack until the base case returns, then the results are multiplied on the way back up.
Each call is pushed onto the call stack with its own parameters, local variables and return address. If there is no base case, the stack fills up and the program crashes with a stack overflow.
| Recursion | Iteration |
|---|---|
| often shorter and closer to the maths | usually faster |
| uses more memory (one stack frame per call) | uses a fixed amount of memory |
| natural for trees and divide-and-conquer | natural for simple repeats |
Check yourself
What happens if a recursive function has no base case?
Show the answer
It calls itself until the call stack overflows
Never stops.
5Strings, random numbers and exceptions
Common string operations:
| Operation | Example | Result |
|---|---|---|
| length | len("pebble") | 6 |
| substring | "pebble"[1:4] | "ebb" |
| position | "pebble".find("b") | 2 |
| concatenation | "peb" + "ble" | "pebble" |
| character code | ord("A") | 65 |
| convert | int("42"), str(42) | 42, "42" |
Random numbers are generated by a pseudo-random algorithm, for example random.randint(1, 6) for a dice roll.
Exception handling stops a program crashing when something goes wrong at run time:
try:
n = int(input("Number: "))
except ValueError:
print("That was not a whole number")
Check yourself
What is "computer"[3:6]?
Show the answer
"put"
Indexes 3, 4, 5.
6Structured programming and trace tables
Structured programming builds a program from small subroutines using only sequence, selection and iteration, with clear interfaces. This makes code easier to read, test and maintain.
A trace table records the value of each variable as a program runs. It is used to find logic errors by hand.
Tracing a loop
- Code: total = 0, then for i in range(1, 4): total = total + i * i.
- i = 1: total = 1.
- i = 2: total = 1 + 4 = 5.
- i = 3: total = 5 + 9 = 14.
Types of test data: normal (typical valid values), boundary (at the edges of the valid range, both just inside and just outside) and erroneous (invalid values that should be rejected).
Check yourself
For an age that must be 0 to 120, which value is boundary data?
Show the answer
120
At the edge.
Now test yourself
This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.
Practise in Impera