AQA 7517, section 4.1.1.2
Almost every program, however large, is built from a small set of statement types. If you can recognise each one and combine them confidently, you can read and write programs in any imperative language. The examples here are in Python.
The statement types
| Statement type | What it does | Example |
|---|---|---|
| Variable declaration | Creates a named place to store a value that can change | score = 0 |
| Constant declaration | Creates a named value that should never change | VAT_RATE = 0.2 |
| Assignment | Stores a value in a variable | score = score + 1 |
| Selection | Chooses which code to run | if, elif, else |
| Iteration | Repeats code | for, while |
| Subroutine | A named block of code you can call | def area(w, h): |
A variable is a named location in memory. The name stays the same while the value can be replaced. A constant is the same idea, but the value is fixed for the whole run. Python has no way to enforce this, so by convention a constant is written in capital letters and you simply don't change it. Many other languages have a keyword (such as const) that stops you changing it.
Assignment puts a value into a variable. It is not the same as "equals" in maths. In score = score + 1, the right-hand side is worked out first using the old value, and the answer is then stored back in score.
MAX_ATTEMPTS = 3 # constant, set once
attempts = 0 # variable declaration and first assignment
attempts = attempts + 1
print(attempts) # 1
Using a constant instead of typing the number everywhere means that if the value ever changes, you edit one line, and the code explains itself. MAX_ATTEMPTS says far more than a bare 3.
The three combining principles
Every program is built by combining just three ideas:
- Sequence: statements run one after another, in order.
- Selection: the program chooses between paths, depending on a condition.
- Iteration: the program repeats a block of statements.
A subroutine lets you wrap a sequence of these up under one name so you can reuse it.
Selection
Selection runs a block of code only if a condition is true. The condition is an expression that gives True or False.
mark = 64
if mark >= 70:
grade = "A"
elif mark >= 60:
grade = "B"
else:
grade = "C or below"
print(grade) # B
Python checks the conditions from the top and runs the first block that is true. The else is a catch-all that runs if none of them were.
Iteration
Iteration means repeating code. There are two kinds, depending on whether you know in advance how many times the loop will run.
Definite iteration
In definite iteration the number of repeats is known when the loop starts. In Python this is usually a for loop.
for i in range(1, 6):
print(i * i) # 1 4 9 16 25
Indefinite iteration
In indefinite iteration the number of repeats is not known in advance. The loop keeps going until a condition changes. In Python this is a while loop.
total = 0
while total < 100:
total = total + 15
print(total) # 105
You couldn't have known without working it out that this loop runs seven times. It stops only when the condition total < 100 becomes false.
Condition at the start or at the end
For indefinite iteration, the condition can be checked in one of two places. You need to understand both, even if the language you use only supports one.
| Condition at the start (pre-condition) | Condition at the end (post-condition) | |
|---|---|---|
| When it is checked | Before each pass | After each pass |
| Minimum number of runs | Zero. If the condition is false at the start, the body never runs. | One. The body always runs once before the first check. |
| Loops while | The condition is true | Usually until the condition becomes true (this varies by language) |
| Typical use | Processing data that might be empty | Asking for input, then checking it |
Python only has the pre-condition loop (while). To get the behaviour of a post-condition loop, run the body first and then test inside the loop:
# The body runs at least once, like a post-condition loop
while True:
pin = input("Enter your 4-digit PIN: ")
if len(pin) == 4 and pin.isdigit():
break
print("That wasn't valid, try again.")
Other languages have this built in, usually written as do ... while or repeat ... until.
Watch out: an indefinite loop must do something that eventually makes its condition change. If nothing in the body ever changes total, the loop above would run forever, which is called an infinite loop.
Nesting
You can put one structure inside another. This is called nesting.
Nested selection is an if inside another if, used when a second decision depends on the first:
age = 17
has_ticket = True
if has_ticket:
if age >= 18:
print("Entry to the main hall")
else:
print("Entry to the family area")
else:
print("Please buy a ticket")
Nested iteration is a loop inside another loop. The inner loop runs fully for every single pass of the outer loop.
for row in range(1, 4):
for col in range(1, 4):
print(row * col, end=" ")
print()
This prints a small multiplication grid:
1 2 3
2 4 6
3 6 9
The outer loop runs 3 times and the inner loop runs 3 times for each of those, so print(row * col) runs 9 times in total.
You can also mix the two, for example a selection inside a loop to handle each item differently:
for n in range(1, 11):
if n % 2 == 0:
print(n, "is even")
Subroutines
A subroutine is a named block of code that you can run (call) whenever you need it. A function returns a value, while a procedure carries out an action without returning one. Python uses def for both. Using subroutines avoids repeating code and breaks a big problem into small parts.
def area(width, height): # function: returns a value
return width * height
def greet(name): # procedure: just does something
print("Hello,", name)
print(area(4, 5)) # 20
greet("Sam") # Hello, Sam
Subroutines are covered in more detail in their own section later in the specification.
Meaningful identifier names
An identifier is the name you give to a variable, constant or subroutine. You should always pick names that describe what the thing is or does.
# Hard to follow
x = 40
y = 12.5
z = x * y
# Easy to follow
hours_worked = 40
hourly_rate = 12.5
weekly_pay = hours_worked * hourly_rate
Meaningful names matter because:
- the code is easier to read and understand, for you and for anyone else;
- it is easier to find and fix mistakes, because it is clear what each part should be doing;
- the code is easier to maintain, because you can see what to change when requirements change;
- it reduces the need for extra comments.
Exam tip: if you're asked why meaningful identifier names are important, don't just say "it's clearer". Link it to a consequence, such as "so another programmer can understand what the variable stores and maintain the program more easily".
Worked example
Task: ask the user for exam marks until they type -1, then print how many marks were entered and the average. Marks must be between 0 and 100.
total = 0
count = 0
mark = 0
# Indefinite iteration, condition at the start
while mark != -1:
mark = int(input("Enter a mark (-1 to finish): "))
# Selection, nested inside the loop
if mark == -1:
print("Finished.")
elif 0 <= mark <= 100:
total = total + mark
count = count + 1
else:
print("Marks must be 0 to 100.")
# Selection, to avoid dividing by zero
if count > 0:
average = total / count
print(count, "marks, average", round(average, 1))
else:
print("No marks entered.")
How it uses the ideas above:
total,countandmarkare variables, each given a starting value (variable declaration and assignment). Startingmarkat 0 means the loop condition is true the first time it is checked.- The
whileloop is indefinite iteration with the condition at the start. We can't know how many marks the user will enter. - The
if,elifandelseinside the loop are nested selection, because they sit inside the iteration. The first branch stops-1being treated as a mark, and the last rejects marks that are out of range. - The final
ifstops the program dividing by zero when no marks were entered. - The names
total,countandaveragetell you what each one stores.
Check yourself
Name the three combining principles used to build programs
Sequence, selection and iteration.
What is the difference between a variable and a constant?
A variable's value can change while the program runs. A constant is given a value once and it should stay the same for the whole run.
Is a for i in range(10) loop definite or indefinite iteration? Why?
Definite, because the number of repeats (10) is known before the loop starts.
Give one difference between a loop with the condition at the start and one with the condition at the end
With the condition at the start, the body might never run, because the condition is checked first. With the condition at the end, the body always runs at least once, because the check happens after the first pass.
How many times does print("*") run here? for a in range(4): for b in range(5): print("*")
20 times. The inner loop runs 5 times for each of the 4 passes of the outer loop, and 4 × 5 = 20.
Why should you use weekly_pay rather than z as a variable name?
It describes what the variable stores, so the code is easier to read, debug and maintain.