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.
DECLARE <identifier> : <datatype>
DECLARE Age : INTEGER
DECLARE Price : REAL
DECLARE GameOver : BOOLEANscore = 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.
| Concept | Cambridge pseudocode | Python |
|---|---|---|
| Variable | DECLARE Age : INTEGER | age = 35 |
| Constant | CONSTANT PI ← 3.142 | PI = 3.142 |
| Constant | CONSTANT PASSWORD ← "letmein" | PASSWORD = "letmein" |
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.
DECLARE Age : INTEGER
DECLARE Price : REAL
DECLARE GameOver : BOOLEANCheck Your Understanding: Variables & Constants
1. What is the main difference between a variable and a constant?
- 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.
2. Why is a data type included in a variable declaration?
- 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.
3. What does DECLARE Age : INTEGER mean?
- 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.
4. Why are constants often written in uppercase?
- 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.
5. Give one suitable use for a variable and one for a constant.
- 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 type | Used for | Pseudocode | Examples |
|---|---|---|---|
| Integer | Whole numbers | INTEGER | 10, -5, 0 |
| Real | Numbers with a fractional part | REAL | 3.14, -2.5, 0.0 |
| Character | Single character | CHAR | 'a', 'B', '6', '£' |
| String | Sequence of characters | STRING | "Hello world", "ABC", "@#!%" |
| Boolean | True or false values | BOOLEAN | TRUE, FALSE |
Data types can be changed within a program; this is called casting.
| Data type | Pseudocode | Python |
|---|---|---|
| Integer | Number ← 5 | number = 5 |
| Real | RealNumber ← 3.14 | realNumber = 3.14 |
| Character | FirstNameInitial ← 'a' | firstNameInitial = 'a' |
| String | Password ← "letmein" | password = "letmein" |
| Boolean | LightSensor ← TRUE | lightSensor = True |
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.
| Value | Type |
|---|---|
| 83 | INTEGER |
| 3.14 | REAL |
| 'A' | CHAR |
| "Hello" | STRING |
| TRUE | BOOLEAN |
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
1. Which data type stores 25.75?
- 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.
2. Which data type is appropriate for the value 'Z'?
- 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.
3. Why is the correct data type important?
- 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.
4. What is casting?
- 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.
5. Give a suitable type for a pass/fail status.
- 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 device | Typical use |
|---|---|
| Keyboard | Typing text |
| Mouse | Selecting items or clicking buttons |
| Sensor | Reading temperature, pressure or motion |
| Microphone | Capturing 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 device | Typical use |
|---|---|
| Monitor | Displaying text, images or graphics |
| Speaker | Playing audio |
| Printer | Creating physical copies |
INPUT Name
IF Name = "James" OR Name = "Rob" THEN
OUTPUT "Great names!"
ENDIFname = input("Enter your name: ")
if name == "James" or name == "Rob":
print("Great names!")Activity 3A: Predict the output
Difficulty: Easy • Estimated time: 5 minutes
What happens when the user enters James?
INPUT Name
IF Name = "James" OR Name = "Rob" THEN
OUTPUT "Great names!"
ENDIFActivity 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
1. What is an input?
- 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.
2. What is an output?
- 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.
3. Why does INPUT make a program interactive?
- 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.
4. What happens when INPUT executes?
- 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.
5. Give an input device and an output device with uses.
- 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.
| Line | Cambridge pseudocode |
|---|---|
| 01 | OUTPUT "Enter the first number" |
| 02 | INPUT Num1 |
| 03 | OUTPUT "Enter the second number" |
| 04 | INPUT Num2 |
| 05 | Result ← Num1 - Num2 |
| 06 | OUTPUT Result |
Swapping line 01 and line 02 gives an unexpected interaction because the user is asked for input before being told what to enter.
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_areadef 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}")Activity 4A: Spot the sequencing error
Difficulty: Easy • Estimated time: 5 minutes
A program returns a result before calculating it. Correct the order.
area ← length * width
RETURN areaActivity 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
1. What is 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.
2. Why can changing INPUT and OUTPUT order cause a problem?
- 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.
3. Why calculate area before RETURN area?
- 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.
4. Give one real-life task where sequence matters.
- 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.
5. How can you check an algorithm sequence?
- 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.
IF <condition> THEN
<statement>
ENDIF| Concept | Cambridge pseudocode | Python |
|---|---|---|
| IF-THEN-ELSE | IF Answer = "Yes" THEN ... ELSE ... ENDIF | if answer == "Yes": ... else: |
| Nested selection | An IF inside another IF | A nested if/elif/else structure |
| CASE | CASE OF identifier ... OTHERWISE ... ENDCASE | Python can emulate using if/elif/else or match/case |
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
ENDIFCASE OF Move
'W' : Position ← Position - 10
'E' : Position ← Position + 10
'A' : Position ← Position - 1
'D' : Position ← Position + 1
OTHERWISE
OUTPUT "Beep"
ENDCASECASE can mean less code when comparing multiple values of the same variable. IF is more flexible and is generally used more in Python.
Activity 5A: Largest of three numbers
Difficulty: Medium • Estimated time: 8 minutes
Write Cambridge pseudocode that inputs three numbers and outputs the largest.
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
ENDIFActivity 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
1. What is 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.
2. What does an IF statement do?
- 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.
3. What is nested selection?
- 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.
4. When is CASE useful?
- 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.
5. Why test selection with several inputs?
- 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.
FOR <identifier> ← <value1> TO <value2>
<statements>
NEXT <identifier>
FOR <identifier> ← <value1> TO <value2> STEP <increment>
<statements>
NEXT <identifier>| Task | Pseudocode | Python |
|---|---|---|
| Print Hello 10 times | FOR X ← 1 TO 10 ... NEXT X | for x in range(10): |
| Even numbers 2 to 10 | FOR X ← 2 TO 10 STEP 2 ... NEXT X | for x in range(2, 12, 2): |
| Count down 10 to 0 | FOR X ← 10 TO 0 STEP -1 ... NEXT X | for x in range(10, -1, -1): |
Condition-controlled loops
| Loop | Behaviour |
|---|---|
| WHILE | Pre-condition: test before each repetition; may execute zero times. |
| REPEAT...UNTIL | Post-condition: test after the body; executes at least once. |
REPEAT
INPUT Colour
UNTIL Colour = "red"WHILE Colour <> "Red" DO
INPUT Colour
ENDWHILENested iteration
A nested loop is a loop within another loop.
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 ", TotalActivity 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.
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"
ENDIFFOR i ← 0 TO 2
FOR j ← 0 TO 1
OUTPUT "(", i, ", ", j, ")"
NEXT j
NEXT iActivity 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
1. What is 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.
2. What is the main difference between FOR and WHILE?
- 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.
3. Why does REPEAT...UNTIL execute at least once?
- 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.
4. What is nested iteration?
- 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.
5. Which loop would you use for displaying 1 to 10 exactly once?
- 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.
Total ← 0
FOR I ← 1 TO 10
INPUT Num
Total ← Total + Num
NEXT I
OUTPUT Totaltotal = 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.
Count ← 0
FOR I ← 1 TO 10
INPUT Num
IF Num > 5 THEN
Count ← Count + 1
ENDIF
NEXT I
OUTPUT CountCount ← 0
FOR x ← 1 TO 20
INPUT Number
IF Number > 50 THEN
Count ← Count + 1
ENDIF
NEXT x
OUTPUT CountActivity 7A: Build a total
Difficulty: Easy • Estimated time: 5 minutes
Write pseudocode that inputs 5 numbers and outputs their total.
Total ← 0
FOR I ← 1 TO 5
INPUT Num
Total ← Total + Num
NEXT I
OUTPUT TotalActivity 7B: Build a count
Difficulty: Easy • Estimated time: 5 minutes
Write pseudocode that inputs 10 marks and counts how many are 80 or above.
Count ← 0
FOR I ← 1 TO 10
INPUT Mark
IF Mark >= 80 THEN
Count ← Count + 1
ENDIF
NEXT I
OUTPUT CountCheck Your Understanding: Totalling & Counting
1. Why is a total usually initialised to 0?
- 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.
2. What is counting used for?
- 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.
3. How would you count numbers greater than 50?
- Start Count at 0.
- Input each number inside a loop.
- Test IF Number > 50 THEN.
- Increase Count by 1 when the condition is TRUE.
4. What is the difference between totalling and counting?
- 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.
5. What is the purpose of the loop in a totalling algorithm?
- 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.
| Operation | Cambridge pseudocode | Python | Output |
|---|---|---|---|
| Uppercase | OUTPUT UCASE(Name) | print(Name.upper()) | SARAH |
| Lowercase | OUTPUT LCASE(Name) | print(Name.lower()) | sarah |
Password ← "letmein"
OUTPUT LENGTH(Password)Password = "letmein"
print(len(Password))| Task | Cambridge pseudocode | Python | Output |
|---|---|---|---|
| First 3 characters of Revision | OUTPUT SUBSTRING(Word, 1, 3) | print(Word[0:3]) | Rev |
| Characters from position 3 for 6 characters | OUTPUT 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.
X ← "Save my exams"
OUTPUT LENGTH(X)
Y ← 9
Z ← 5
OUTPUT SUBSTRING(X, Y, Z)Activity 8A: Password check
Difficulty: Easy • Estimated time: 5 minutes
Write pseudocode that accepts a password only when its length is at least 8.
INPUT Password
IF LENGTH(Password) >= 8 THEN
OUTPUT "Password accepted"
ELSE
OUTPUT "Password too short"
ENDIFActivity 8B: Extract a word
Difficulty: Medium • Estimated time: 6 minutes
Store “Save my exams” in X and output “exams” using the source substring approach.
X ← "Save my exams"
Y ← 9
Z ← 5
OUTPUT SUBSTRING(X, Y, Z)Check Your Understanding: String Handling
1. What is string manipulation?
- 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.
2. What does LENGTH do?
- It counts characters in a string.
- It can be used for password validation.
- The result is numeric.
- Python uses len() in the source example.
3. What is a substring?
- 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.
4. Why must students be careful about substring positions?
- 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.
5. How can “Sarah” be changed to upper and lower case?
- 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.
| Operation | Pseudocode | Python |
|---|---|---|
| Addition | + | + |
| Subtraction | - | - |
| Multiplication | * | * |
| Division | / | / |
| Modulus (remainder) | MOD | % |
| Quotient (whole-number division) | DIV | // |
| Exponentiation | ^ | ** |
| Comparison | Pseudocode | Python |
|---|---|---|
| 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.
user_input = int(input("Enter a number: "))
if user_input % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")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)Activity 9A: Odd or even
Difficulty: Easy • Estimated time: 5 minutes
Write the Cambridge condition for testing whether an integer is even.
IF Number MOD 2 = 0 THEN
OUTPUT "Even"
ELSE
OUTPUT "Odd"
ENDIFActivity 9B: Combine conditions
Difficulty: Easy • Estimated time: 5 minutes
Write a condition that is TRUE only when score is from 90 to 100 inclusive.
IF score >= 90 AND score <= 100 THEN
OUTPUT "Grade: A"
ENDIFFive-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
1. What does MOD give you?
- 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.
2. What does DIV give you?
- 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.
3. What does AND mean?
- 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.
4. What does NOT do?
- NOT reverses a Boolean condition.
- TRUE becomes FALSE.
- FALSE becomes TRUE.
- The notes warn that NOT can be misunderstood.
5. Why combine comparison and Boolean operators?
- 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.
PROCEDURE <identifier>
<statements>
ENDPROCEDURE
PROCEDURE <identifier>(<param1> : <data type>, <param2> : <data type>)
<statements>
ENDPROCEDURE
CALL <identifier>
CALL <identifier>(Value1, Value2)PROCEDURE CalculateArea(length : INTEGER, width : INTEGER)
area ← length * width
OUTPUT "The area is ", area
ENDPROCEDURE
CALL CalculateArea(5, 3)FUNCTION CalculateArea(length : INTEGER, width : INTEGER) RETURNS INTEGER
area ← length * width
RETURN area
ENDFUNCTION
OUTPUT CalculateArea(5, 3)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.
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.
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
1. What is a sub-program?
- 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.
2. What is a parameter?
- 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.
3. What is the main difference between a procedure and a function?
- 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.
4. Why are sub-programs useful?
- They reduce duplication.
- They improve readability and maintainability.
- They can be reused.
- They divide a large problem into smaller parts.
5. Why should CALL not be used for a function?
- 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.
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.
globalVariable = 10
def print_value():
global globalVariable
print("The value into the variable is:", globalVariable)
print_value()| Local | Global |
|---|---|
| Declared inside a function or block | Declared outside functions/procedures |
| Accessible only in its scope | Accessible across the program |
| Lifetime limited to the block | Available throughout the program |
| Helps keep sub-programs self-contained | Can 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.
Activity 11A: Scope detective
Difficulty: Easy • Estimated time: 5 minutes
Identify which variable is local and which is global in the examples.
| Variable | Scope |
|---|---|
| localVariable | Local to print_value() |
| globalVariable | Global 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
1. What is a local variable?
- 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.
2. What is a global variable?
- 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.
3. Why can local variables improve maintainability?
- 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.
4. When might a global variable be useful?
- 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.
5. What is a risk of using a global variable carelessly?
- 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.
| Routine | Purpose |
|---|---|
| MOD | Computes the remainder after division. |
| DIV | Computes the whole-number quotient. |
| ROUND | Rounds a numerical value. |
| RANDOM | Generates a random integer within a range. |
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:", resultresult ← RANDOM(1, 6)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.
DECLARE Price : REAL
DECLARE RoundedPrice : REAL
Price ← 12.6789
RoundedPrice ← ROUND(Price, 2)
OUTPUT "The rounded price is ", RoundedPriceThe 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] ← Numberimport 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)Activity 12A: Choose the routine
Difficulty: Easy • Estimated time: 5 minutes
Match remainder, quotient, rounding and random integer to MOD, DIV, ROUND and RANDOM.
| Task | Routine |
|---|---|
| Remainder | MOD |
| Whole-number quotient | DIV |
| Round a value | ROUND |
| Random integer | RANDOM |
Activity 12B: Use ROUND
Difficulty: Easy • Estimated time: 5 minutes
Write pseudocode that stores 12.6789 and outputs it rounded to 2 decimal places.
DECLARE Price : REAL
DECLARE RoundedPrice : REAL
Price ← 12.6789
RoundedPrice ← ROUND(Price, 2)
OUTPUT "The rounded price is ", RoundedPriceCheck Your Understanding: Library Routines
1. What is a library routine?
- 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.
2. What is MOD used for?
- 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.
3. What is DIV used for?
- 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.
4. Give two uses of random numbers.
- 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.
5. Why can library routines make programming faster?
- 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.
| Technique | Why it helps |
|---|---|
| Layout | Spaces sections clearly. |
| Indentation | Shows code structure. |
| Comments | Explain key parts of the code. |
| Meaningful variable names | Describe what is stored. |
| White space | Improves readability. |
| Sub-programs | Break the solution into manageable functions or procedures. |
When these techniques are used consistently, programs are easier to maintain.
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()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
1. What is maintainability?
- 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.
2. Why are meaningful variable names important?
- 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.
3. How does indentation help?
- It shows program structure.
- It makes nested blocks easier to identify.
- It improves readability.
- The notes explicitly recommend indentation.
4. Why are comments useful?
- 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.
5. Why can sub-programs improve maintainability?
- 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
1. Explain the difference between a variable and a constant. [5 marks]
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.
2. Describe the five basic data types used in the lesson. [4 marks]
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.
3. Explain how INPUT and OUTPUT work. [4 marks]
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.
4. Explain sequence, selection and iteration. [4 marks]
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.
5. Compare FOR, WHILE and REPEAT...UNTIL. [4 marks]
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.
6. Explain nested statements and give two examples. [4 marks]
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.
7. Describe totalling and counting. [4 marks]
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.
8. Explain the difference between substring positions in pseudocode and Python. [4 marks]
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.
9. Explain arithmetic, logical and Boolean operators. [5 marks]
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.
10. Explain procedures, functions and parameters. [5 marks]
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.
11. Explain local and global variables. [4 marks]
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.
12. Explain library routines and MOD, DIV, ROUND and RANDOM. [4 marks]
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.
13. Describe five techniques that improve program maintainability. [5 marks]
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.
14. Write Cambridge pseudocode to input 20 numbers and count how many are greater than 50. [4 marks]
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.
15. Explain when CASE is useful and when IF may be preferable. [5 marks]
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
The attached notes include these video resources.