AxoPrep

Computer Science

B2.3 Programming constructs

The building blocks of every program: sequence, selection, iteration, functions with parameters and return values, and variable scope. Study guide, 4 practice questions with markschemes and 4 flashcards. Free.

sequence · selection with if/else · loops and iteration · functions and modular code · scope of variables

Practise all 4 questions Study 4 flashcards

Study guide

Sequence

Statements run one after another, top to bottom. Order matters: swapping two lines can change the result.

price = 40
price = price * 0.9   # 10% off -> 36.0
price = price + 5     # delivery -> 41.0

Doing the delivery first would give 40.5 instead.

Selection

if / elif / else picks one branch. Conditions are checked in order and only the first true branch runs, so put the most specific test first.

def grade(score):
    if score >= 80:
        return "A"
    elif score >= 65:
        return "B"
    elif score >= 50:
        return "C"
    else:
        return "U"

Combine conditions with and, or, not. A range check: if 1 <= n <= 10: in Python, if (n >= 1 && n <= 10) in Java.

Iteration

range(start, stop, step) stops before stop: range(1, 10, 4) gives 1, 5, 9.

Nested loop trace:

total = 0
for i in range(1, 4):
    for j in range(i, 4):
        total = total + 1
print(total)
iinner j valuesiterationstotal
11, 2, 333
22, 325
3316

Output: 6.

Java input validation with a post-condition loop:

int age;
do {
    System.out.print("Age (13-19): ");
    age = input.nextInt();
} while (age < 13 || age > 19);
System.out.println("Accepted " + age);

Functions and modular code

A function (method in Java) is a named block that can take parameters and return a value. Benefits: code is written once and reused, each part can be tested separately, programs are easier to read, and team members can work on different modules.

def count_between(values, low, high):
    count = 0
    for v in values:
        if low <= v <= high:
            count = count + 1
    return count

print(count_between([4, 12, 7, 20, 9], 5, 10))   # 2
public static int countBetween(int[] values, int low, int high) {
    int count = 0;
    for (int v : values) {
        if (v >= low && v <= high) count++;
    }
    return count;
}

A parameter is the name in the definition (values); an argument is the actual value passed in the call. return ends the function immediately; print only displays and gives nothing back to the caller.

Scope of variables

level = 1

def level_up(level):
    level = level + 1
    return level

new = level_up(level)
print(level, new)   # 1 2

The parameter level is a new local variable that happens to share a name with the global one. Changing it does not touch the global. Locals reduce accidental side effects and make functions self-contained; overuse of globals makes bugs hard to trace.

Common mistakes

Exam tips

Cheat sheet

ConstructPythonJava
Selectionif / elif / elseif / else if / else, switch
Count loopfor i in range(a, b, s)for (int i = a; i < b; i += s)
Pre-condition loopwhile cond:while (cond) { }
Post-condition loopwhile True: ... breakdo { } while (cond);
Functiondef f(x): return ystatic int f(int x) { return y; }
AND / OR / NOTand or not&& `\\ !`

Key definitions

Sequence

Executing statements one after another in the order they are written.

Selection

Choosing which statements to execute based on whether a condition is true or false.

Iteration

Repeating a block of statements, either a set number of times or until a condition changes.

Function

A named, reusable block of code that may take parameters and return a value.

Parameter

A variable named in a function's definition that receives a value when the function is called.

Argument

The actual value supplied to a function when it is called.

Return value

The result a function sends back to the code that called it.

Local variable

A variable declared inside a function that can only be used within that function while it runs.

Global variable

A variable declared outside all functions that can be accessed anywhere in the program file.

Practice questions

SLPaper 2Foundation

Question 1

(a) [2]

State the output of the following code.

for i in range(2, 11, 3):
    print(i * i)
Markscheme
  • 1 i takes the values 2, 5, 8 (stops before 11)
  • 1 Output: 4, 25, 64 on separate lines
(b) [2]

State the final value of count.

count = 0
for i in range(4):
    for j in range(i):
        count = count + 1
Markscheme
  • 1 Inner loop runs 0, 1, 2, 3 times for i = 0, 1, 2, 3
  • 1 count = 6
SLPaper 2Challenging

Question 2

(a) [6]

Construct a Python function average_above(values, limit) that returns the mean of all numbers in the list values that are greater than limit. If no number is greater than limit, the function must return 0.

Markscheme
  • 1 Initialises a total and a counter to 0
  • 1 Loops over every item in the list
  • 1 Selects only items greater than limit
  • 1 Accumulates total and count correctly
  • 1 Returns 0 when count is 0 (avoids division by zero)
  • 1 Otherwise returns total / count
(b) [1]

State the value returned by average_above([4, 12, 7, 15, 9], 8).

Markscheme
  • 1 12 (or 12.0): (12 + 15 + 9) / 3
SLPaper 2Standard

Question 3

(a) [1]

State the output of this program.

total = 10

def add_bonus(total):
    total = total + 5
    return total

result = add_bonus(total)
print(total, result)
Markscheme
  • 1 10 15
(b) [2]

Explain why the value of the global total does not change.

Markscheme
  • 1 The parameter total is a separate local variable inside the function
  • 1 Changing it does not affect the global variable; only the returned value is stored in result
(c) [1]

Outline one advantage of using local variables rather than global variables.

Markscheme
  • 1 Functions are independent / reusable and cannot accidentally change data used elsewhere, making debugging easier

Key facts

What does range(2, 11, 3) produce?

2, 5, 8. The stop value (11) is never included.

Local vs global variable

Local: exists only inside the function where it is created. Global: visible throughout the program. Prefer locals plus parameters and return values.

Count-controlled vs condition-controlled loop

Count-controlled (for): repeats a known number of times. Condition-controlled (while): repeats until a condition changes.

Common mistake: return -1 inside the loop

In a search, returning "not found" inside the loop stops after the first item. Return it only after the loop ends.