B2.3 Programming Constructs

Sequence, selection, loops and functions. All examples use Python.

Contents
ConstructMeaningPython
SequenceInstructions run one after another, in order.line by line
SelectionChoose 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'?
ProblemWhat happensAvoid it by
Infinite loopEnd condition never met, e.g. counter never updated.Update the loop variable inside the loop.
DeadlockTwo processes each hold a resource the other needs, so neither continues.Sequence steps so resources are used and released at different times.
Incorrect inputUnexpected 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.

PartRuns 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

OperatorMeaningx = 100
==equal to (two equals signs, one = assigns)x == 100 → True
!=not equal tox != 50 → True
> <greater than, less thanx > 150 → False
>= <=greater or equal, less or equalx >= 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

PythonJavaTrue whenExample
and&&both conditions are Trueit is sunny and warm
or||at least one is Trueit is sunny or warm
not!the condition is Falseit 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 loopfor loop
TypeCondition controlled (indefinite)Count controlled (definite)
Use whenNumber of repeats unknownNumber of repeats known, or every item in a list
Watch outChecked 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.

AdvantageWhy
Easier to readNamed blocks show what each part does.
Easier to testEach function tested on its own.
Easier to reuseWrite once, call many times or import elsewhere.
Easier to updateChange it in one place only.
TeamworkModules 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
TermMeaningIn the example
Function signatureThe 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 valueThe result sent back to the line that called it.volume
Local variableCreated inside the function, only exists while it runs.volume
Global variableCreated 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 libraryUsed for
randomPseudorandom numbers and choices
mathMathematical functions (sqrt, pi, floor, ceil)
datetimeDates and times
osAccess 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

With and, every condition must be True for the if statement to run its code [1]. With or, only one of the conditions needs to be True [1]. For example, if age >= 18 and has_ticket: needs both, while if day == "Sat" or day == "Sun": runs on either day [1].
Saves time: the code is already written [1], so the programmer does not have to write common functions such as random numbers or square roots from scratch [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
Marks: function defined with a sensible name [1], radius as a parameter [1], correct formula πr² [1], result returned [1].

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")
Marks: clues stored in a list [1], loop that gives one clue per pass [1], input and comparison with the answer [1], loop ends when guessed or clues run out [1], correct output for win and lose [1].
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(...)).
Ninja Notes: