B2.3 Programming Constructs
Sequence, selection, loops and functions. All examples use Python.
| Construct | Meaning | Python |
|---|---|---|
| Sequence | Instructions run one after another, in order. | line by line |
| Selection | Choose a path depending on a condition. | if elif else match |
| Repetition (iteration) | Repeat a block of code. | while for |
B2.3.1: Sequence
Sequence: instructions run in the order written. Wrong order = wrong result or crash.
total = price * quantity # used before it exists
price = 20
quantity = 3
print("Total:", total)
NameError: name 'price' is not defined. Did you mean: 'print'?
| Problem | What happens | Avoid it by |
|---|---|---|
| Infinite loop | End condition never met, e.g. counter never updated. | Update the loop variable inside the loop. |
| Deadlock | Two processes each hold a resource the other needs, so neither continues. | Sequence steps so resources are used and released at different times. |
| Incorrect input | Unexpected input crashes the program or gives wrong results. | Validate input (B2.1.3). |
B2.3.2: Selection
Selection: a condition is tested and the program takes a different path depending on whether it is True or False.
| Part | Runs when |
|---|---|
if condition: | the condition is True |
elif condition: (optional, any number) | every condition above was False and this one is True |
else: (optional, last) | nothing above was True. The catch all. |
Only the first True branch runs, so order matters. After age <= 5, the next check only needs age <= 12.
def suggest(age):
if age < 0 or age > 100:
return "Invalid age"
elif age <= 5:
return "Soft play centre"
elif age <= 12:
return "Trip to the park"
elif age <= 18:
return "Meet up with friends"
else:
return "Go to the movies"
for a in [3, 12, 13, 40, 150]:
print(a, suggest(a))
3 Soft play centre 12 Trip to the park 13 Meet up with friends 40 Go to the movies 150 Invalid age
Comparison operators
| Operator | Meaning | x = 100 |
|---|---|---|
== | equal to (two equals signs, one = assigns) | x == 100 → True |
!= | not equal to | x != 50 → True |
> < | greater than, less than | x > 150 → False |
>= <= | greater or equal, less or equal | x >= 100 → True |
They also work on strings (alphabetical, character by character), so "9" > "10" is True. Convert input with int() before comparing numbers.
Logical operators
| Python | Java | True when | Example |
|---|---|---|---|
and | && | both conditions are True | it is sunny and warm |
or | || | at least one is True | it is sunny or warm |
not | ! | the condition is False | it is not raining |
The textbook says ! is "not" in Python. Wrong: Python uses not.
Case statements: match
Compares one value against several options. Alternative to a long elif chain. Python: match, Java: switch. case _ = else.
day = "Sun"
match day:
case "Sat" | "Sun":
print("Weekend")
case "Fri":
print("Almost weekend")
case _:
print("Weekday")
Weekend
B2.3.3: Loops
| while loop | for loop | |
|---|---|---|
| Type | Condition controlled (indefinite) | Count controlled (definite) |
| Use when | Number of repeats unknown | Number of repeats known, or every item in a list |
| Watch out | Checked before each pass, may run 0 times. Can loop forever. | range(a, b) stops before b |
while
n = 1
steps = 0
while n <= 100: # checked BEFORE every pass
n = n * 2
steps = steps + 1
print(n, "after", steps, "doublings")
128 after 7 doublings
Password with 3 attempts:
PASSWORD = "ninja"
attempts = 0
correct = False
while attempts < 3 and not correct:
guess = input("Password: ")
attempts = attempts + 1
if guess == PASSWORD:
correct = True
else:
print("Wrong password")
if correct:
print("Logged in")
else:
print("Locked out")
for
for i in range(1, 6):
print(i, "* 10 =", i * 10)
1 * 10 = 10 2 * 10 = 20 3 * 10 = 30 4 * 10 = 40 5 * 10 = 50
print(list(range(5))) # 0 up to 4
print(list(range(2, 6))) # 2 up to 5
print(list(range(10, 0, -2))) # count down in steps of 2
[0, 1, 2, 3, 4] [2, 3, 4, 5] [10, 8, 6, 4, 2]
Looping through a list (linear search):
team = ["Heather", "Toni", "Francesca", "Ben", "Syed",
"Wes", "Toni", "Ife", "Chidi", "Taro"]
count = 0
for name in team:
if name == "Toni":
count = count + 1
print("Number of Tonis:", count)
Number of Tonis: 2
Nested loop: the inner loop runs fully for each pass of the outer one (used for 2D lists).
B2.3.4: Functions and Modularization
Modularization: splitting code into separate functions or modules, each doing one task. Function: a named block of code that performs a task when called.
| Advantage | Why |
|---|---|
| Easier to read | Named blocks show what each part does. |
| Easier to test | Each function tested on its own. |
| Easier to reuse | Write once, call many times or import elsewhere. |
| Easier to update | Change it in one place only. |
| Teamwork | Modules built in parallel. |
Anatomy of a function
def rectangle_volume(w, h, d): # w, h, d are parameters
volume = w * h * d # local variable
return volume # send the answer back
print(rectangle_volume(10, 20, 10)) # 10, 20, 10 are arguments
width = 3
height = 4
depth = 5
v = rectangle_volume(width, height, depth)
print("Volume:", v)
2000 Volume: 60
| Term | Meaning | In the example |
|---|---|---|
| Function signature | The name plus the parameters it expects. | rectangle_volume(w, h, d) |
| Parameters (formal) | The placeholders in the definition that receive values. | w, h, d |
| Arguments (actual parameters) | The real values or variables sent in when the function is called. | 10, 20, 10 or width, height, depth |
| Return value | The result sent back to the line that called it. | volume |
| Local variable | Created inside the function, only exists while it runs. | volume |
| Global variable | Created outside any function, can be read anywhere. | width |
return vs print
return sends a value back to use. print only displays it. No return gives None.
Libraries
Library: pre written, pre tested modules you import. Saves time, fewer bugs.
| Python library | Used for |
|---|---|
random | Pseudorandom numbers and choices |
math | Mathematical functions (sqrt, pi, floor, ceil) |
datetime | Dates and times |
os | Access to the operating system (files, folders) |
import random, math
random.choice(students) # random item
random.randint(1, 6) # 1 to 6 inclusive
math.sqrt(81) # 9.0
Never name your file random.py: it would be imported instead of the library.
Practice Questions
if age >= 18 and has_ticket: needs both, while if day == "Sat" or day == "Sun": runs on either day [1].
Reliable: library code has already been tested by many users [1], so it is less likely to contain bugs than new code [1].
import math
def circle_area(radius):
return math.pi * radius ** 2
print(round(circle_area(5), 2))
78.54
The user is given clues one at a time and must guess the celebrity. The game ends when the name is guessed (or the clues run out).
ANSWER = "usain bolt"
clues = ["I am an athlete", "I am from Jamaica", "I run very fast",
"I won 8 Olympic golds", "My pose looks like a lightning bolt"]
clue_number = 0
guessed = False
while clue_number < len(clues) and not guessed:
print("Clue", clue_number + 1, ":", clues[clue_number])
guess = input("Who am I? ").lower()
if guess == ANSWER:
guessed = True
else:
print("Not quite")
clue_number = clue_number + 1
if guessed:
print("Correct! You needed", clue_number + 1, "clues")
else:
print("Out of clues. It was Usain Bolt")
price = input("User One, enter the price")
guess = input("User Two, enter your guess")
if guess > price:
print("too high")
What goes wrong if the price is 10 and the guess is 9?
input() always returns a string, so "9" > "10" compares text and is True. The program says 9 is "too high". Fix: price = int(input(...)) and guess = int(input(...)).
- Sequence, selection, iteration: the three building blocks of every program.
- if / elif / else runs only the first True branch. Order your conditions carefully.
=assigns,==compares. Convert input withint()before comparing numbers.- and = both, or = at least one, not = flip.
- for = count controlled (known number). while = condition controlled (unknown number).
range(1, 6)gives 1 to 5. The stop value is never included.- Parameters are in the definition, arguments are in the call. return sends a value back.
- Modularization makes code easier to read, test, reuse and update.