PC

8.1 Programming Concepts

Programming concepts: variables, data types, input/output and program control structures

Learning Objectives

By the end of this lesson, you will be able to:

  • Declare and use variables and constants using Cambridge IGCSE pseudocode and Python.
  • Choose and use INTEGER, REAL, CHAR, STRING and BOOLEAN appropriately.
  • Use INPUT and OUTPUT correctly and explain common input and output devices.
  • Apply sequence, selection and iteration, including IF, CASE, FOR, WHILE and REPEAT...UNTIL.
  • Use nested statements, totalling and counting to solve programming problems.
  • Manipulate strings using length, substring, uppercase, lowercase and character positions.
  • Use arithmetic, logical and Boolean operators correctly.
  • Define and call procedures and functions, with and without parameters.
  • Explain local and global variables and their scope.
  • Use library routines such as MOD, DIV, ROUND and RANDOM.
  • Write maintainable programs using clear layout, indentation, comments, meaningful names, white space and sub-programs.

Key Terms

  • Variable- An identifier whose stored value can change while the program runs.
  • Constant- An identifier whose value is set once and is not changed during the program.
  • Data type- A classification that describes the kind of data a variable stores.
  • Integer- A whole number.
  • Real- A number with a fractional part.
  • Character (CHAR)- A single character.
  • String- A sequence of characters.
  • Boolean- A value that is TRUE or FALSE.
  • Casting- Changing data from one data type to another.
  • Input- A value read from an input device.
  • Output- A value sent to an output device.
  • Sequence- Executing instructions in order.
  • Selection- Choosing which statements execute according to a condition.
  • Iteration- Repeating a statement or block using a loop.
  • Nested statement- A statement placed inside another statement.
  • Parameter- A placeholder that receives a value when a sub-program is called.
  • Procedure- A sub-program that performs a task and does not return a value.
  • Function- A sub-program that performs a task and returns a value.
  • Local variable- A variable available only in its defined scope.
  • Global variable- A variable declared outside sub-programs and accessible across the program.
  • Library routine- Reusable code provided through a library or module.
  • Maintainability- How easy a program is to read, understand, modify and manage.

Variables & Constants

A variable is an identifier that can change during the lifetime of a program. The notes describe identifiers as mixed case (Pascal case), using letters and digits and starting with a capital letter rather than a digit. Declaring a variable associates it with a data type and memory is allocated according to that type.

  • Use a variable when the stored value may change.
  • Declare the data type so the program knows what kind of value is stored.
  • Cambridge pseudocode uses DECLARE <identifier> : <datatype>.
  • Examples include Age : INTEGER, Price : REAL and GameOver : BOOLEAN.
Cambridge IGCSE pseudocode
DECLARE <identifier> : <datatype>
DECLARE Age : INTEGER
DECLARE Price : REAL
DECLARE GameOver : BOOLEAN
Python
score = int()
cost = float()
light = bool()

What is a constant?

  • A constant is an identifier set once during the lifetime of a program.
  • Constants are generally named in uppercase characters.
  • Constants aid readability and maintainability.
  • If a constant needs changing, it should only need to be altered in one place.
ConceptCambridge pseudocodePython
VariableDECLARE Age : INTEGERage = 35
ConstantCONSTANT PI ← 3.142PI = 3.142
ConstantCONSTANT PASSWORD ← "letmein"PASSWORD = "letmein"
Real-life example:A current score can change, so it is a variable. A fixed rate or maximum score can be represented as a constant.

Activity 1A: Variable or constant?

Difficulty: Easy • Estimated time: 5 minutes

Decide which should be variables or constants: currentScore, SCHOOL_NAME, VAT_RATE, numberOfAttempts.

  • currentScore → variable because it can change.
  • SCHOOL_NAME → constant when fixed for the program.
  • VAT_RATE → constant when fixed for the program.
  • numberOfAttempts → variable because it changes as attempts are made.

Activity 1B: Declaration practice

Difficulty: Easy • Estimated time: 5 minutes

Write Cambridge pseudocode to declare Age as INTEGER, Price as REAL and GameOver as BOOLEAN.

Answer
DECLARE Age : INTEGER
DECLARE Price : REAL
DECLARE GameOver : BOOLEAN

Check Your Understanding: Variables & Constants

  • A variable may change while the program runs.
  • A constant is set once and is not changed during execution.
  • Variables suit values such as scores that change.
  • Constants suit fixed values such as rates or limits.
  • It tells the program what kind of value the variable will store.
  • It helps determine how the value is represented and stored.
  • It reduces the chance of using an unsuitable type.
  • The notes link memory allocation to the declared data type.
  • Age is the identifier being declared.
  • INTEGER is the data type.
  • The program creates a variable named Age.
  • The variable is intended to store a whole number.
  • The source notes state that constants are generally named using uppercase characters.
  • The convention makes constants easy to recognise.
  • It improves readability when scanning a program.
  • It communicates that the value is intended to remain fixed.
  • A changing score is suitable for a variable.
  • A fixed maximum score is suitable for a constant.
  • The score may be updated during execution.
  • The maximum should remain unchanged unless the program is edited.

Data Types

A data type classifies data according to the kind of value it represents. The notes identify five basic data types and stress choosing the correct type for accuracy and efficiency.

Data typeUsed forPseudocodeExamples
IntegerWhole numbersINTEGER10, -5, 0
RealNumbers with a fractional partREAL3.14, -2.5, 0.0
CharacterSingle characterCHAR'a', 'B', '6', '£'
StringSequence of charactersSTRING"Hello world", "ABC", "@#!%"
BooleanTrue or false valuesBOOLEANTRUE, FALSE

Data types can be changed within a program; this is called casting.

Data typePseudocodePython
IntegerNumber ← 5number = 5
RealRealNumber ← 3.14realNumber = 3.14
CharacterFirstNameInitial ← 'a'firstNameInitial = 'a'
StringPassword ← "letmein"password = "letmein"
BooleanLightSensor ← TRUElightSensor = True
Real-life example:A student age is an INTEGER, temperature may be REAL, an initial is CHAR, a name is STRING and a yes/no status can be BOOLEAN.

Activity 2A: Match the data type

Difficulty: Easy • Estimated time: 5 minutes

Match 83, 3.14, 'A', "Hello" and TRUE to their most suitable types.

ValueType
83INTEGER
3.14REAL
'A'CHAR
"Hello"STRING
TRUEBOOLEAN

Activity 2B: Choose the correct type

Difficulty: Easy • Estimated time: 5 minutes

A program stores a mark, name, first initial and whether homework was submitted. Choose a suitable type for each.

  • Mark → INTEGER.
  • Name → STRING.
  • First initial → CHAR.
  • Homework submitted → BOOLEAN.

Check Your Understanding: Data Types

  • REAL is suitable because the value contains a fractional part.
  • INTEGER would not be appropriate because it stores whole numbers.
  • A real value can include decimals.
  • Using REAL represents the value accurately.
  • CHAR is suitable because it stores a single character.
  • The value contains one character.
  • CHAR differs from STRING, which stores a sequence.
  • A character is shown in single quotes in the source examples.
  • It supports accurate representation of the data.
  • It can make operations appropriate and efficient.
  • It reduces the chance of treating data as the wrong kind.
  • The notes explicitly link correct types with accuracy and efficiency.
  • Casting means changing data from one type to another.
  • A value can be converted to another required type.
  • Casting changes the representation used by the program.
  • The source notes name this process casting.
  • BOOLEAN is appropriate because there are two logical states.
  • TRUE can represent one state and FALSE the other.
  • It clearly represents a yes/no condition.
  • Using BOOLEAN communicates the meaning directly.

Input & Output

What is an input?

  • An input is a value read from an input device and processed by a program.
  • Typical input devices include keyboards, mice, sensors and microphones.
  • Without inputs, programs cannot interact with the outside world and would always produce the same result.
  • The keyboard is the standard user-input device in the notes.
  • When INPUT executes, the program waits for the user to type a sequence of characters.
Input deviceTypical use
KeyboardTyping text
MouseSelecting items or clicking buttons
SensorReading temperature, pressure or motion
MicrophoneCapturing audio or speech

What is an output?

  • An output is a value sent from a computer program to an output device.
  • Typical output devices include a monitor, speaker and printer.
  • The monitor is the standard user-output device in the notes.
  • OUTPUT sends information to the screen in Cambridge pseudocode.
Output deviceTypical use
MonitorDisplaying text, images or graphics
SpeakerPlaying audio
PrinterCreating physical copies
Cambridge pseudocode
INPUT Name
IF Name = "James" OR Name = "Rob" THEN
    OUTPUT "Great names!"
ENDIF
Python
name = input("Enter your name: ")
if name == "James" or name == "Rob":
    print("Great names!")
Real-life example:A school login gets a username from the keyboard, processes it, and displays a welcome message on the monitor.

Activity 3A: Predict the output

Difficulty: Easy • Estimated time: 5 minutes

What happens when the user enters James?

Answer: the condition is TRUE, so the program outputs "Great names!"
INPUT Name
IF Name = "James" OR Name = "Rob" THEN
    OUTPUT "Great names!"
ENDIF

Activity 3B: Identify input and output

Difficulty: Easy • Estimated time: 5 minutes

For a temperature-monitoring system, identify one input device and one output device.

  • Input example: a temperature sensor.
  • The sensor supplies temperature data to the program.
  • Output example: a monitor or display.
  • The program can show the processed temperature to the user.

Check Your Understanding: Input & Output

  • It is a value read from an input device.
  • The value is then processed by the program.
  • A keyboard entry is a typical example.
  • Sensors and microphones can also provide input.
  • It is a value sent from a program to an output device.
  • A monitor can display it.
  • A speaker can play it as sound.
  • A printer can create a physical copy.
  • INPUT allows the user or device to provide data.
  • The program can work with different values each time it runs.
  • It allows responses to changing outside information.
  • The notes describe input as essential for interaction.
  • The program waits for input.
  • The data is stored in the named identifier.
  • The program does not continue past the INPUT until data is supplied.
  • Keyboard input is the standard case described in the notes.
  • Keyboard → type text.
  • Sensor → read a physical measurement.
  • Monitor → display text, images or graphics.
  • Printer → create a physical copy.

Sequence

Sequence means executing lines of code one at a time in their written order. It is fundamental to program flow; an instruction out of sequence can cause unexpected behaviour or errors.

LineCambridge pseudocode
01OUTPUT "Enter the first number"
02INPUT Num1
03OUTPUT "Enter the second number"
04INPUT Num2
05Result ← Num1 - Num2
06OUTPUT Result

Swapping line 01 and line 02 gives an unexpected interaction because the user is asked for input before being told what to enter.

Correct Cambridge pseudocode
FUNCTION CalculateArea(length, width)
    area ← length * width
    RETURN area
ENDFUNCTION

length ← 5
width ← 3
correct_area ← CalculateArea(length, width)
OUTPUT "Correct area (length * width): ", correct_area
Correct Python
def calculate_area(length, width):
    area = length * width
    return area

length = 5
width = 3
correct_area = calculate_area(length, width)
print(f"Correct area (length * width): {correct_area}")
Real-life example:A school order system might choose an item before entering quantity, calculate the total after both inputs, then display the total.

Activity 4A: Spot the sequencing error

Difficulty: Easy • Estimated time: 5 minutes

A program returns a result before calculating it. Correct the order.

Correct order
area ← length * width
RETURN area

Activity 4B: Trace the steps

Difficulty: Easy • Estimated time: 5 minutes

State Result when Num1 = 15 and Num2 = 7.

  • Num1 receives 15.
  • Num2 receives 7.
  • Result is calculated as 15 - 7.
  • Result therefore stores 8.

Check Your Understanding: Sequence

  • It is execution of instructions in order.
  • The program moves from one instruction to the next.
  • Each instruction is carried out according to its position.
  • Correct sequence supports predictable behaviour.
  • The user may be asked for data without being told what to enter.
  • This makes the interaction confusing.
  • The program may not behave as intended.
  • The source example shows this when lines are swapped.
  • RETURN needs a value to return.
  • If area has not been assigned, there is no calculated result.
  • The incorrect order causes a runtime error in the source example.
  • The correct sequence is calculate first, return second.
  • An order system must receive the item before calculating price.
  • It must receive quantity before calculating the total.
  • The total should be calculated before display.
  • Changing the order can cause missing or incorrect information.
  • Read each instruction in execution order.
  • Check that each step has the required information.
  • Check that calculations occur before their results are used.
  • Test with sample input and inspect the result.

Selection

Selection changes program flow according to a condition. The notes identify IF...THEN...ELSE...ENDIF and CASE as the two main forms.

Cambridge pseudocode syntax
IF <condition> THEN
    <statement>
ENDIF
ConceptCambridge pseudocodePython
IF-THEN-ELSEIF Answer = "Yes" THEN ... ELSE ... ENDIFif answer == "Yes": ... else:
Nested selectionAn IF inside another IFA nested if/elif/else structure
CASECASE OF identifier ... OTHERWISE ... ENDCASEPython can emulate using if/elif/else or match/case
Nested selection from the notes
IF Player2Score > Player1Score THEN
    IF Player2Score > HighScore THEN
        OUTPUT Player2, " is champion and highest scorer"
    ELSE
        OUTPUT Player2, " is the new champion"
    ENDIF
ELSE
    OUTPUT Player1, " is still the champion"
    IF Player1Score > HighScore THEN
        OUTPUT Player1, " is also the highest scorer"
    ENDIF
ENDIF
Cambridge CASE example
CASE OF Move
    'W' : Position ← Position - 10
    'E' : Position ← Position + 10
    'A' : Position ← Position - 1
    'D' : Position ← Position + 1
    OTHERWISE
        OUTPUT "Beep"
ENDCASE

CASE can mean less code when comparing multiple values of the same variable. IF is more flexible and is generally used more in Python.

Real-life example:A school attendance system can choose an action from a student status, while a menu can choose one action from several fixed values.

Activity 5A: Largest of three numbers

Difficulty: Medium • Estimated time: 8 minutes

Write Cambridge pseudocode that inputs three numbers and outputs the largest.

Exemplar solution
INPUT A
INPUT B
INPUT C
IF A >= B AND A >= C THEN
    OUTPUT A
ELSE IF B >= A AND B >= C THEN
    OUTPUT B
ELSE
    OUTPUT C
ENDIF

Activity 5B: Choose IF or CASE

Difficulty: Medium • Estimated time: 5 minutes

When is CASE suitable for a menu choice?

  • CASE is suitable when one variable is compared with several fixed values.
  • It can make pseudocode shorter and clearer.
  • IF is more flexible for complex conditions.
  • The notes state that CASE is useful for multiple values of the same variable.

Check Your Understanding: Selection

  • Selection changes program flow according to a condition.
  • The condition determines which statements execute.
  • It is useful for validation and user choices.
  • IF and CASE are the two forms identified in the notes.
  • It checks a condition.
  • TRUE causes the associated statements to execute.
  • An ELSE can provide an alternative for FALSE.
  • ENDIF marks the end of the Cambridge IF structure.
  • It is one selection statement inside another.
  • The inner decision is reached through the outer structure.
  • It allows a second decision to be made after the first.
  • The notes use nested IF statements as an example.
  • It is useful when comparing multiple values of one variable.
  • It can reduce repeated IF statements.
  • Each value can have a different action.
  • OTHERWISE handles values not listed.
  • Different values may follow different branches.
  • Testing one value can miss another path.
  • Important conditions and outcomes should all be checked.
  • The notes recommend testing with various inputs.

Iteration

Iteration repeats a line or block of code using a loop. The notes describe count-controlled, condition-controlled and nested iteration.

Cambridge FOR syntax
FOR <identifier> ← <value1> TO <value2>
    <statements>
NEXT <identifier>

FOR <identifier> ← <value1> TO <value2> STEP <increment>
    <statements>
NEXT <identifier>
TaskPseudocodePython
Print Hello 10 timesFOR X ← 1 TO 10 ... NEXT Xfor x in range(10):
Even numbers 2 to 10FOR X ← 2 TO 10 STEP 2 ... NEXT Xfor x in range(2, 12, 2):
Count down 10 to 0FOR X ← 10 TO 0 STEP -1 ... NEXT Xfor x in range(10, -1, -1):

Condition-controlled loops

LoopBehaviour
WHILEPre-condition: test before each repetition; may execute zero times.
REPEAT...UNTILPost-condition: test after the body; executes at least once.
Cambridge pseudocode
REPEAT
    INPUT Colour
UNTIL Colour = "red"
Cambridge pseudocode
WHILE Colour <> "Red" DO
    INPUT Colour
ENDWHILE

Nested iteration

A nested loop is a loop within another loop.

Nested-loop example
Total ← 0
FOR Row ← 1 TO MaxRow
    RowTotal ← 0
    FOR Column ← 1 TO 10
        RowTotal ← RowTotal + Amount[Row, Column]
    NEXT Column
    OUTPUT "Total for Row ", Row, " is ", RowTotal
    Total ← Total + RowTotal
NEXT Row
OUTPUT "The grand total is ", Total
Real-life example:A school report system can use an outer loop for classes and an inner loop for students in each class.

Activity 6A: Choose the right loop

Difficulty: Medium • Estimated time: 8 minutes

Choose FOR, WHILE or REPEAT...UNTIL for fixed repetitions, a temperature condition and an input-until-correct task.

  • Fixed number of repetitions → FOR.
  • Temperature condition checked before each repetition → WHILE.
  • Input until correct → REPEAT...UNTIL.
  • Each choice matches the loop control described in the notes.

Activity 6B: Trace a count-down

Difficulty: Easy • Estimated time: 5 minutes

What values are output by FOR X ← 10 TO 0 STEP -1?

  • The values are 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 and 0.
  • The starting value is 10.
  • STEP -1 decreases the counter by one.
  • The loop finishes after 0 is reached.

Nested Statements — additional TED-note section

The TED notes explicitly cover nested statements: nesting means putting one statement inside another, including selection inside selection and loops inside loops.

Nested selection
x ← 10
y ← 5
IF x > 0 THEN
    OUTPUT "x is positive"
    IF y > 0 THEN
        OUTPUT "y is also positive"
    ELSE
        OUTPUT "y is not positive"
    ENDIF
ELSE
    OUTPUT "x is not positive"
ENDIF
Nested iteration
FOR i ← 0 TO 2
    FOR j ← 0 TO 1
        OUTPUT "(", i, ", ", j, ")"
    NEXT j
NEXT i

Activity N1: Trace nested loops

Difficulty: Medium • Estimated time: 5 minutes

How many pairs are output by the nested FOR example?

  • The outer loop runs for 0, 1 and 2: three times.
  • The inner loop runs for 0 and 1: two times per outer value.
  • Therefore 3 × 2 = 6 pairs are output.
  • The pairs are (0,0), (0,1), (1,0), (1,1), (2,0) and (2,1).

Check Your Understanding: Iteration

  • Iteration repeats a line or block of code.
  • A loop controls the repetition.
  • Iteration can be count-controlled, condition-controlled or nested.
  • Loops avoid repeatedly writing identical instructions.
  • FOR is commonly used when the number of repetitions is known.
  • WHILE repeats while its condition is TRUE.
  • FOR uses an integer counter in the notes.
  • WHILE may execute zero times when its initial condition is FALSE.
  • The condition is tested after the loop body.
  • Therefore the body must execute before the first test.
  • The loop then stops when the condition becomes TRUE.
  • This is the key difference from a pre-condition loop.
  • It is a loop inside another loop.
  • The inner loop completes within each outer-loop iteration.
  • It is useful for tables and two-dimensional data.
  • The notes show nested loops for rows and columns.
  • A FOR loop is appropriate.
  • The number of repetitions is fixed.
  • The counter can run from 1 TO 10.
  • This directly matches a count-controlled task.

Totalling & Counting

Totalling

Totalling means adding values together, often inside a loop. The total variable starts at 0.

Cambridge pseudocode
Total ← 0
FOR I ← 1 TO 10
    INPUT Num
    Total ← Total + Num
NEXT I
OUTPUT Total
Python
total = 0
for i in range(1, 11):
    num = int(input("Enter a number: "))
    total = total + num
print("Total:", total)

Counting

Counting tracks how many times an event occurs. Count starts at 0 and is increased when the condition is met.

Cambridge pseudocode
Count ← 0
FOR I ← 1 TO 10
    INPUT Num
    IF Num > 5 THEN
        Count ← Count + 1
    ENDIF
NEXT I
OUTPUT Count
3-mark exemplar
Count ← 0
FOR x ← 1 TO 20
    INPUT Number
    IF Number > 50 THEN
        Count ← Count + 1
    ENDIF
NEXT x
OUTPUT Count
Real-life example:A school can total test marks and count how many students score above a threshold.

Activity 7A: Build a total

Difficulty: Easy • Estimated time: 5 minutes

Write pseudocode that inputs 5 numbers and outputs their total.

Answer
Total ← 0
FOR I ← 1 TO 5
    INPUT Num
    Total ← Total + Num
NEXT I
OUTPUT Total

Activity 7B: Build a count

Difficulty: Easy • Estimated time: 5 minutes

Write pseudocode that inputs 10 marks and counts how many are 80 or above.

Answer
Count ← 0
FOR I ← 1 TO 10
    INPUT Mark
    IF Mark >= 80 THEN
        Count ← Count + 1
    ENDIF
NEXT I
OUTPUT Count

Check Your Understanding: Totalling & Counting

  • 0 is the neutral starting value for addition.
  • Each input can then be added to the running total.
  • Starting at another value changes the final result.
  • The source example explicitly sets Total ← 0.
  • It records how many times an event happens.
  • A count variable is increased when a condition is satisfied.
  • The counter normally starts at 0.
  • The final count can be output after the loop.
  • Start Count at 0.
  • Input each number inside a loop.
  • Test IF Number > 50 THEN.
  • Increase Count by 1 when the condition is TRUE.
  • Totalling adds values together.
  • Counting records how many values meet a condition.
  • The total stores an accumulated sum.
  • The count stores the number of qualifying occurrences.
  • It repeats the input and addition steps.
  • It lets the same logic handle several values.
  • Each value is added to the current total.
  • Without repetition only one input value would be processed.

String Handling

String manipulation uses programming techniques to modify, analyse or extract information from a string.

OperationCambridge pseudocodePythonOutput
UppercaseOUTPUT UCASE(Name)print(Name.upper())SARAH
LowercaseOUTPUT LCASE(Name)print(Name.lower())sarah
Cambridge pseudocode
Password ← "letmein"
OUTPUT LENGTH(Password)
Python
Password = "letmein"
print(len(Password))
TaskCambridge pseudocodePythonOutput
First 3 characters of RevisionOUTPUT SUBSTRING(Word, 1, 3)print(Word[0:3])Rev
Characters from position 3 for 6 charactersOUTPUT SUBSTRING(Word, 3, 6)print(Word[2:8])vision

The source notes emphasise that substring start positions use 1 in pseudocode and 0 in Python.

Cambridge pseudocode exemplar
X ← "Save my exams"
OUTPUT LENGTH(X)
Y ← 9
Z ← 5
OUTPUT SUBSTRING(X, Y, Z)
Real-life example:An app can change a name to uppercase, check a password length or extract part of an email address.

Activity 8A: Password check

Difficulty: Easy • Estimated time: 5 minutes

Write pseudocode that accepts a password only when its length is at least 8.

Answer
INPUT Password
IF LENGTH(Password) >= 8 THEN
    OUTPUT "Password accepted"
ELSE
    OUTPUT "Password too short"
ENDIF

Activity 8B: Extract a word

Difficulty: Medium • Estimated time: 6 minutes

Store “Save my exams” in X and output “exams” using the source substring approach.

Answer
X ← "Save my exams"
Y ← 9
Z ← 5
OUTPUT SUBSTRING(X, Y, Z)

Check Your Understanding: String Handling

  • It is using programming techniques to modify, analyse or extract information from strings.
  • Case conversion modifies a string.
  • Length analyses a string.
  • Substring extracts part of a string.
  • It counts characters in a string.
  • It can be used for password validation.
  • The result is numeric.
  • Python uses len() in the source example.
  • It is a sequence of characters extracted from a larger string.
  • It can be used in validation.
  • It can be combined with other strings.
  • The source notes use slicing to extract characters.
  • The notes use a start position of 1 in pseudocode.
  • Python starts indexing at 0.
  • The same string can therefore require different position values.
  • The language being written must be considered.
  • Use UCASE(Name) in the Cambridge pseudocode example.
  • Use LCASE(Name) in the Cambridge pseudocode example.
  • Use .upper() in Python.
  • Use .lower() in Python.

Arithmetic, Logical & Boolean Operators

An operator is a symbol used to instruct a computer to perform an operation on one or more values.

OperationPseudocodePython
Addition++
Subtraction--
Multiplication**
Division//
Modulus (remainder)MOD%
Quotient (whole-number division)DIV//
Exponentiation^**
ComparisonPseudocodePython
Equal to====
Not equal to<>!=
Less than<<
Less than or equal to<=<=
Greater than>>
Greater than or equal to>=>=
  • AND returns TRUE when both conditions are TRUE.
  • OR returns TRUE when one or both conditions are TRUE.
  • NOT returns the opposite Boolean value.
  • Boolean operators are often used with comparison operators in IF and loops.
Python: odd/even
user_input = int(input("Enter a number: "))
if user_input % 2 == 0:
    print("The number is even.")
else:
    print("The number is odd.")
Python: circle area
radius = float(input("Enter the radius of the circle: "))
area = 3.14159 * radius ** 2
print("The area of the circle with radius", radius, "is", area)
Real-life example:A school door can open when a valid ID is scanned AND the student is permitted to enter.

Activity 9A: Odd or even

Difficulty: Easy • Estimated time: 5 minutes

Write the Cambridge condition for testing whether an integer is even.

Answer
IF Number MOD 2 = 0 THEN
    OUTPUT "Even"
ELSE
    OUTPUT "Odd"
ENDIF

Activity 9B: Combine conditions

Difficulty: Easy • Estimated time: 5 minutes

Write a condition that is TRUE only when score is from 90 to 100 inclusive.

Answer
IF score >= 90 AND score <= 100 THEN
    OUTPUT "Grade: A"
ENDIF

Five-question maths quiz example

The source notes include a Python program that generates five maths questions, accepts an operator (+, - or *), checks each answer and keeps a score.

score = 0
for x in range(5):
    num1 = int(input("Enter the first number: "))
    operator = input("Enter the operator (+, -, *): ")
    num2 = int(input("Enter the second number: "))
    user_answer = int(input("What is " + str(num1) + " " + str(operator) + " " + str(num2) + "? "))
    if operator == '+':
        correct_answer = num1 + num2
    elif operator == '-':
        correct_answer = num1 - num2
    elif operator == '*':
        correct_answer = num1 * num2
    else:
        print("Invalid operator!")
        continue
    if user_answer == correct_answer:
        score = score + 1
    else:
        print("Sorry, that's incorrect.")
print("Your score is:", score)

Check Your Understanding: Operators

  • MOD gives the remainder after division.
  • For example, 7 MOD 2 gives 1.
  • It is useful for odd/even tests.
  • Python uses % for this operation.
  • DIV gives the whole-number quotient.
  • It ignores the fractional part.
  • Python uses // for whole-number division.
  • The notes list DIV as a quotient operation.
  • Both conditions must be TRUE.
  • A FALSE condition makes the combined AND result FALSE.
  • It is commonly used inside IF statements.
  • The notes give an example using two comparisons with AND.
  • NOT reverses a Boolean condition.
  • TRUE becomes FALSE.
  • FALSE becomes TRUE.
  • The notes warn that NOT can be misunderstood.
  • Comparison operators produce TRUE or FALSE.
  • Boolean operators combine those results.
  • This allows more complex conditions.
  • The source notes explicitly mention this combination.

Procedures & Functions

Procedures and functions are sub-programs: sequences of instructions that perform specific tasks. They help break a program into smaller, manageable parts.

  • Sub-programs avoid duplicated code and can be reused.
  • They improve readability and maintainability.
  • They can perform calculations, retrieve data or make decisions.
  • Parameters are values or variables passed into a sub-program.
  • Functions return a value; procedures do not.
Cambridge procedure structure
PROCEDURE <identifier>
    <statements>
ENDPROCEDURE

PROCEDURE <identifier>(<param1> : <data type>, <param2> : <data type>)
    <statements>
ENDPROCEDURE

CALL <identifier>
CALL <identifier>(Value1, Value2)
Procedure example
PROCEDURE CalculateArea(length : INTEGER, width : INTEGER)
    area ← length * width
    OUTPUT "The area is ", area
ENDPROCEDURE

CALL CalculateArea(5, 3)
Function example
FUNCTION CalculateArea(length : INTEGER, width : INTEGER) RETURNS INTEGER
    area ← length * width
    RETURN area
ENDFUNCTION

OUTPUT CalculateArea(5, 3)
Python exemplar based on the airline-ticket task
def flightCost(passengers, ticket_type):
    if ticket_type == "economy":
        cost = 199 * passengers
    elif ticket_type == "first":
        cost = 595 * passengers
    return cost

print(flightCost(3, "economy"))

The notes emphasise: in Cambridge pseudocode, do not use CALL for a function; use the function in an expression such as OUTPUT CalculateArea(5,3). CALL is used for procedures.

Real-life example:A school reporting system can use one function to calculate a total and a procedure to display a menu. The same sub-program can be reused.

Activity 10A: Procedure or function?

Difficulty: Medium • Estimated time: 6 minutes

Classify: display a menu; calculate an average; print a warning message.

  • display a menu → procedure.
  • calculate an average → function because a result can be returned.
  • print a warning message → procedure.
  • The key test is whether a value is returned.

Activity 10B: Build a function

Difficulty: Medium • Estimated time: 6 minutes

Write a function that receives length and width and returns rectangle area.

Answer
FUNCTION CalculateArea(length : INTEGER, width : INTEGER) RETURNS INTEGER
    area ← length * width
    RETURN area
ENDFUNCTION

OUTPUT CalculateArea(5, 3)

Procedure menu example from the notes

The notes also show a Python program where a main menu calls addition, subtraction, multiplication, division and exit procedures. No parameters are needed for these procedures.

# Procedure definition for the main menu
def main_menu():
    print("1. Addition")
    print("2. Subtraction")
    print("3. Multiplication")
    print("4. Division")
    print("5. Exit")
    choice = int(input("Enter your choice: "))
    if choice == 1:
        addition()
    elif choice == 2:
        subtraction()
    elif choice == 3:
        multiplication()
    elif choice == 4:
        division()
    elif choice == 5:
        exit_program()

def addition():
    num1 = int(input("Enter the first number: "))
    num2 = int(input("Enter the second number: "))
    print("Result:", num1 + num2)

def subtraction():
    num1 = int(input("Enter the first number: "))
    num2 = int(input("Enter the second number: "))
    print("Result:", num1 - num2)

def multiplication():
    num1 = int(input("Enter the first number: "))
    num2 = int(input("Enter the second number: "))
    print("Result:", num1 * num2)

def division():
    num1 = int(input("Enter the first number: "))
    num2 = int(input("Enter the second number: "))
    if num2 != 0:
        print("Result:", num1 / num2)
    else:
        print("Error: Division by zero is not allowed.")

def exit_program():
    print("Exiting the program. Goodbye!")
    exit()

while True:
    main_menu()

Check Your Understanding: Procedures & Functions

  • It is a sequence of instructions that performs a specific task.
  • Procedures and functions are examples.
  • Breaking programs into sub-programs makes them more manageable.
  • Sub-programs can be reused.
  • A parameter is a placeholder that receives a value when a sub-program is called.
  • It is written in brackets after the sub-program name.
  • A sub-program can have multiple parameters.
  • Parameters can be values or variables.
  • A function returns a value.
  • A procedure does not return a value.
  • Functions are used in expressions because they produce results.
  • Procedures are called using CALL in Cambridge pseudocode.
  • They reduce duplication.
  • They improve readability and maintainability.
  • They can be reused.
  • They divide a large problem into smaller parts.
  • A function returns a value.
  • The function can be used inside an expression.
  • For example, OUTPUT CalculateArea(5,3) uses the result.
  • CALL is used for procedures that do not return a value.

Local & Global Variables

Local variables

A local variable is declared within a specific scope such as a function or block. It is accessible only within that scope, and its lifetime is limited to that block.

Python local-variable example
def print_value():
    localVariable = 10
    print("The value of the local variable is:", localVariable)

print_value()
  • Local variables help keep a sub-program self-contained.
  • They exist only while the sub-program or block is running.
  • They can make sub-programs easier to reuse without interfering with other modules.
  • The notes describe them as memory-efficient because they exist only where needed.

Global variables

A global variable is declared at the outermost level of a program, outside functions or procedures. It has global scope.

Python global-variable example
globalVariable = 10

def print_value():
    global globalVariable
    print("The value into the variable is:", globalVariable)

print_value()
LocalGlobal
Declared inside a function or blockDeclared outside functions/procedures
Accessible only in its scopeAccessible across the program
Lifetime limited to the blockAvailable throughout the program
Helps keep sub-programs self-containedCan be shared by several modules

The TED notes also illustrate a dice-game example where local variables x and y are used inside subroutines while a shared score is global.

Real-life example:A temporary calculation used only inside one function is local; a shared term value used by several routines is global.

Activity 11A: Scope detective

Difficulty: Easy • Estimated time: 5 minutes

Identify which variable is local and which is global in the examples.

VariableScope
localVariableLocal to print_value()
globalVariableGlobal to the program

Activity 11B: Prefer local scope

Difficulty: Medium • Estimated time: 5 minutes

Give one advantage of making a variable local when it is only needed inside one sub-program.

  • It keeps the sub-program self-contained.
  • Other parts of the program cannot accidentally change it.
  • The variable exists only while it is needed.
  • This can make the program easier to maintain and debug.

Check Your Understanding: Local & Global Variables

  • It is declared within a specific scope.
  • It can be accessed only inside that scope.
  • Its lifetime is limited to the block or sub-program.
  • Functions and code blocks can provide such scopes.
  • It is declared at the outermost level.
  • It is outside sub-programs such as functions or procedures.
  • It can be accessed from different parts of the program.
  • The notes describe it as having global scope.
  • They keep a sub-program self-contained.
  • They reduce interference between separate parts of the program.
  • They make sub-programs easier to reuse with their own working variables.
  • They can make debugging easier because their scope is limited.
  • When several parts of the program need the same value.
  • The value can be shared by more than one sub-program.
  • The source dice-game example uses a shared score.
  • The programmer must understand its wider scope.
  • More parts of the program can change it.
  • A change in one sub-program may affect another.
  • Bugs can be harder to trace.
  • Using local variables where possible keeps responsibilities clearer.

Library Routines

A library routine is reusable code made available through reusable modules or functions. Using library routines saves time because working code has already been tested.

RoutinePurpose
MODComputes the remainder after division.
DIVComputes the whole-number quotient.
ROUNDRounds a numerical value.
RANDOMGenerates a random integer within a range.
Cambridge pseudocode example
DECLARE number1, number2, result : INTEGER
number1 ← 15
number2 ← 7
result ← MOD(number1, number2)
OUTPUT "MOD Result:", result
result ← DIV(number1, number2)
OUTPUT "DIV Result:", result
DECLARE decimalNumber : REAL
decimalNumber ← 7.8
result ← ROUND(decimalNumber)
OUTPUT "ROUND Result:", result
result ← RANDOM(10)
OUTPUT "RANDOM Result:", result
Cambridge pseudocode: random integer
result ← RANDOM(1, 6)
Python: random integer
import random
number = random.randint(1, 10)

The notes give uses for random numbers including simulating a dice roll, selecting a random question, the national lottery and cryptography.

ROUND example
DECLARE Price : REAL
DECLARE RoundedPrice : REAL
Price ← 12.6789
RoundedPrice ← ROUND(Price, 2)
OUTPUT "The rounded price is ", RoundedPrice

The output shown in the notes is:The rounded price is 12.68.

Random choice and national lottery example

The notes also show random choice and a national-lottery example that creates available numbers, chooses six numbers, removes chosen numbers, sorts them, and outputs the winning numbers.

RandomIndex ← ROUND((RANDOM() * (50 - Count)), 0)
IF RandomIndex = 0 THEN
    RandomIndex ← 1
ENDIF
Number ← LotteryNumbers[RandomIndex]
ChosenNumbers[Count] ← Number
import random

lottery_numbers = list(range(1, 50))
chosen_numbers = []

for _ in range(6):
    number = random.choice(lottery_numbers)
    chosen_numbers.append(number)
    lottery_numbers.remove(number)

chosen_numbers.sort()
print("The winning numbers are:", chosen_numbers)
Real-life example:A game can use RANDOM to simulate a dice roll; a shop can use ROUND when displaying a price.

Activity 12A: Choose the routine

Difficulty: Easy • Estimated time: 5 minutes

Match remainder, quotient, rounding and random integer to MOD, DIV, ROUND and RANDOM.

TaskRoutine
RemainderMOD
Whole-number quotientDIV
Round a valueROUND
Random integerRANDOM

Activity 12B: Use ROUND

Difficulty: Easy • Estimated time: 5 minutes

Write pseudocode that stores 12.6789 and outputs it rounded to 2 decimal places.

Answer
DECLARE Price : REAL
DECLARE RoundedPrice : REAL
Price ← 12.6789
RoundedPrice ← ROUND(Price, 2)
OUTPUT "The rounded price is ", RoundedPrice

Check Your Understanding: Library Routines

  • It is reusable code provided through a library or module.
  • It can be used by different parts of a program.
  • Using one can save development time.
  • The notes describe library code as already tested.
  • MOD returns the remainder after division.
  • For example, 15 MOD 7 gives 1.
  • It is useful for odd/even tests.
  • Python uses % for the same operation.
  • DIV returns a whole-number quotient.
  • It removes the fractional part.
  • Python uses // for whole-number division.
  • The notes list DIV as a library routine example.
  • A program can simulate a dice roll.
  • It can select a random question.
  • The notes also mention the national lottery and cryptography.
  • Randomness adds unpredictability.
  • The programmer does not have to write every routine from scratch.
  • Reusable code has already been made available.
  • The notes describe it as working and tested code.
  • The programmer can concentrate on the rest of the problem.

Maintaining Programs

Maintainable programs are written so code is easy to read, understand and modify. The notes emphasise consistency.

TechniqueWhy it helps
LayoutSpaces sections clearly.
IndentationShows code structure.
CommentsExplain key parts of the code.
Meaningful variable namesDescribe what is stored.
White spaceImproves readability.
Sub-programsBreak the solution into manageable functions or procedures.

When these techniques are used consistently, programs are easier to maintain.

Maintainable Python example based on the notes
def calculate_area_of_triangle(base, height):
    if base <= 0 or height <= 0:
        raise ValueError("Base and height must be positive values.")
    area = 0.5 * base * height
    return area

def main():
    try:
        base = float(input("Enter the base of the triangle: "))
        height = float(input("Enter the height of the triangle: "))
        area = calculate_area_of_triangle(base, height)
        print(f"The area of the triangle is approximately {area:.2f} square units.")
    except ValueError as error:
        print(f"Error: {error}")

main()
Real-life example:A school management program may be maintained by different programmers. Clear names, comments and sub-programs make changes easier.

Activity 13A: Improve the code

Difficulty: Easy • Estimated time: 5 minutes

List four changes that would make a messy program easier to maintain.

  • Use meaningful variable and function names.
  • Use consistent indentation and layout.
  • Add comments to explain important sections.
  • Break large blocks into suitable functions or procedures.

Activity 13B: Maintainability check

Difficulty: Medium • Estimated time: 6 minutes

Identify one feature that improves structure, one that improves validation and one that improves reuse in the triangle program.

  • Structure: consistent indentation and separated functions make the program clearer.
  • Validation: the program checks that base and height are positive.
  • Reuse: calculate_area_of_triangle() can be called by main().
  • Meaningful names such as base, height and area improve readability.

Check Your Understanding: Maintaining Programs

  • It is how easy a program is to read and modify.
  • Maintainable code is easier to understand later.
  • Clear structure supports future changes.
  • The notes link maintainability with consistent techniques.
  • They describe what data is stored.
  • They make code easier to read.
  • They reduce the need to guess meanings.
  • They help future programmers understand the program.
  • It shows program structure.
  • It makes nested blocks easier to identify.
  • It improves readability.
  • The notes explicitly recommend indentation.
  • Comments explain key parts of the code.
  • They help another programmer understand a section.
  • They are useful when logic is not obvious.
  • The notes list comments as a maintainability technique.
  • They split a large solution into smaller pieces.
  • Each piece can have a clear purpose.
  • They reduce duplicated code.
  • Smaller organised parts are easier to test and modify.

Key Takeaways

  • Use DECLARE with a data type for Cambridge pseudocode variables.
  • Use CONSTANT for fixed values; variables can change.
  • Choose the basic data type that matches the value.
  • INPUT brings data in; OUTPUT sends data out.
  • Sequence = order; selection = decision; iteration = repetition.
  • FOR is count-controlled; WHILE is pre-condition; REPEAT...UNTIL is post-condition.
  • Nested statements place one selection or loop inside another.
  • Totalling starts at 0 and adds values; counting starts at 0 and counts qualifying values.
  • Use LENGTH, SUBSTRING, UCASE and LCASE for string handling in the source examples.
  • Remember MOD, DIV, arithmetic, comparison and Boolean operators.
  • Procedures do not return a value; functions do.
  • Use local variables for values needed only inside a scope; globals can be shared.
  • Library routines save time; RANDOM and ROUND are key source examples.
  • Maintainable code uses layout, indentation, comments, meaningful names, white space and sub-programs.

Question Bank

Answer / Marking Points
  • A variable is an identifier whose value can change during the program.
  • A constant is an identifier whose value is set once.
  • Variables suit changing values such as scores or counters.
  • Constants suit fixed values such as rates or limits.
  • A changed constant should only need editing in one place.
Answer / Marking Points
  • INTEGER stores whole numbers.
  • REAL stores numbers with a fractional part.
  • CHAR stores one character and STRING stores a sequence of characters.
  • BOOLEAN stores TRUE or FALSE values.
Answer / Marking Points
  • INPUT reads a value from an input device.
  • The program processes the input value.
  • OUTPUT sends a value from the program to an output device.
  • Keyboard and monitor are the standard input and output devices in the notes.
Answer / Marking Points
  • Sequence executes instructions in order.
  • Selection chooses statements according to conditions.
  • Iteration repeats instructions using loops.
  • Together they form the core program-flow structures in the source material.
Answer / Marking Points
  • FOR is count-controlled and suits a fixed number of repetitions.
  • WHILE is pre-condition and can execute zero times.
  • REPEAT...UNTIL is post-condition and executes at least once.
  • The condition for WHILE is tested before the body, while REPEAT tests after the body.
Answer / Marking Points
  • A nested statement is placed inside another statement.
  • Nested selection puts an IF inside another IF.
  • Nested iteration puts one loop inside another.
  • The notes show both forms using Cambridge pseudocode.
Answer / Marking Points
  • Totalling adds values to a running total.
  • The total is normally initialised to 0.
  • Counting records how many times a condition or event occurs.
  • The count is normally initialised to 0 and increased when the condition is TRUE.
Answer / Marking Points
  • The notes use a start position of 1 in pseudocode.
  • Python indexing starts at 0.
  • The same characters can therefore require different positions.
  • Students must use the indexing convention of the language being written.
Answer / Marking Points
  • Arithmetic operators perform calculations.
  • MOD gives a remainder and DIV gives a whole-number quotient.
  • Comparison operators compare values and produce Boolean results.
  • AND, OR and NOT combine or reverse Boolean conditions.
  • These operators are used in calculations, IF statements and loop conditions.
Answer / Marking Points
  • A procedure performs a task without returning a value.
  • A function performs a task and returns a value.
  • A parameter is a placeholder that receives a value when the sub-program is called.
  • Procedures use CALL in Cambridge pseudocode, while functions are used within expressions.
  • Sub-programs reduce duplication and improve readability and maintainability.
Answer / Marking Points
  • A local variable is declared inside a scope and is accessible only there.
  • Its lifetime is limited to its scope.
  • A global variable is declared outside sub-programs and can be accessed from different parts of the program.
  • Local variables help keep sub-programs self-contained, while globals allow shared data.
Answer / Marking Points
  • Library routines provide reusable code and save programming time.
  • MOD returns a remainder and DIV returns a whole-number quotient.
  • ROUND rounds a numeric value.
  • RANDOM generates a random integer within a specified range.
Answer / Marking Points
  • Use clear layout and spacing.
  • Use indentation to show structure.
  • Use comments to explain important code.
  • Use meaningful variable and function names.
  • Use white space and sub-programs to keep the solution organised and reusable.
Answer / Marking Points
  • Initialise Count to 0.
  • Use FOR x ← 1 TO 20 and INPUT Number.
  • Use IF Number > 50 THEN and increase Count by 1.
  • OUTPUT Count after the loop.
Answer / Marking Points
  • CASE is useful when comparing multiple fixed values of one variable.
  • CASE can reduce repeated selection code.
  • Each listed value can have its own action.
  • IF is more flexible for ranges and more complex conditions.
  • The notes state that IF is generally more flexible in Python.

Source Resources in the Notes