Skip to content

2029–2031 edition · for exams from June 2029. Students sitting exams up to November 2028 follow the current course.

2210 · 04782029–2031 editionPaper 2 · Algorithms and Programming§8.1, §8.2

8. Programming fundamentals

Python 3.10+ from the start: variables and constants, int/float/str/bool and casting, input and output, if/elif/else, match-case, for and while loops, totalling and counting, string methods and operators.

What you need to know29 learning objectives, as printed in the syllabus

  1. 8.1Programming conceptsNow in Python2026–2028 syllabus: §8.1

    Written in Python 3.10+: int, float, str, bool, casting, if/elif/else, match-case, for, while, while True … break, string methods.

    Learning objectives (6)
    • 8.1.1Understand the purpose of variables and constants and initialise them in Python
    • 8.1.2Identify and use the basic data types: (a) (int) integer; (b) (float) real; (c) (str) string; (d) (bool) Boolean
    • 8.1.3Use casting to convert between the data types in 8.1.2
    • 8.1.4Identify and use inputs and outputs
    • 8.1.5Demonstrate and use the following programming constructs: (a) sequence; (b) selection — if, elif and else statements; nested selection; match-case; (c) iteration — for loop (count-controlled); while loop (pre-condition); while, break (post-condition loop); nested iteration (loops); (d) Understand and use the concepts of totalling and counting
    • 8.1.6Demonstrate and use the concept of string handling, including: (a) len() length; (b) .find() find the position of a substring; (c) .count() count substrings; (d) .upper() uppercase; (e) .lower() lowercase; (f) .title() title case; (g) .replace() replace; (h) + concatenation

    The first character of the string is position zero

  2. 8.2Programming operatorsNow in Python2026–2028 syllabus: §8.1

    Python operators: / is float division, // floor division, % modulus, ** power; and, or, not.

    Learning objectives (3)
    • 8.2.1Demonstrate and use arithmetic operators, limited to: (a) + (addition); (b) – (subtraction); (c) / (float division); (d) * (multiplication); (e) ** (raise to the power of); (f) % (modulus division); (g) // (floor division)
    • 8.2.2Demonstrate and use relational operators, limited to: (a) == equal to; (b) != not equal to; (c) < less than; (d) <= less than or equal to; (e) > greater than; (f) >= greater than or equal to
    • 8.2.3Demonstrate and use logical operators, limited to: (a) and; (b) or; (c) not

Objectives quoted from the 2029–2031 syllabus, Version 1, September 2026; © Cambridge University Press & Assessment.

Notes2every learning objective explained, with worked examples

8.1Programming concepts

The building blocks of every Python program: storing data in variables and constants with the right data type, converting between types, input and output, and the three constructs — sequence, selection and iteration — plus totalling, counting and string handling.

Variables and constants

  • A variable is a named memory location whose value can change while the program runs.
  • A constant is a named value that does not change while the program runs. Python has no constant keyword, so by convention constants are written in CAPITALS and never re-assigned.
  • Initialise = give a starting value before it is used.
MAX_STUDENTS = 30     # constant
VAT_RATE = 0.2        # constant
total = 0             # variable initialised to 0
name = ""             # variable initialised to an empty string

Why constants? The value is changed in one place only, the name explains the value, and it cannot be changed by mistake elsewhere.

Data types and casting

TypePythonExample
Integerint42, -7
Realfloat3.5, -0.25
Stringstr"Hello", "0300"
BooleanboolTrue, False

Casting converts one type to another: int(), float(), str(), bool().

age = int("16")          # str -> int: 16
price = float("2.5")     # str -> float: 2.5
label = "Age: " + str(age)
whole = int(7.9)         # float -> int: 7 (cuts off, does not round)
print(label, price, whole)

Output: Age: 16 2.5 7. A phone number or ID with a leading 0 should be a string.

Input and output

input() always returns a string, so cast it when you need a number. print() outputs; separate items with commas (adds a space) or join strings with +.

name = input("Enter your name: ")
mark = int(input("Enter your mark: "))
print("Well done", name, "you scored", mark)

Sequence and selection

Sequence = statements run one after another in order. Selection = choosing a path with if / elif / else, nested ifs or match-case.

mark = int(input("Mark: "))
if mark >= 70:
    grade = "A"
elif mark >= 50:
    grade = "B"
else:
    grade = "U"
print(grade)

day = input("Day: ")
match day:
    case "Saturday" | "Sunday":
        print("Weekend")
    case "Friday":
        print("Nearly the weekend")
    case _:
        print("School day")

A nested selection is an if inside another if — used when a second question only matters after the first is true. case _ catches every other value.

Iteration: for, while and the post-condition loop

  • Count-controlled — for repeats a known number of times. range(1, 6) gives 1 to 5 (the stop value is not included).
  • Pre-condition — while condition: tests before each pass, so it may run zero times.
  • Post-condition — Python writes it as while True: with an if … break at the end: the body always runs at least once.
  • Nested iteration — a loop inside a loop (e.g. rows and columns).
for count in range(1, 6):
    print(count * count)

password = ""
while password != "secret":
    password = input("Password: ")

while True:
    choice = input("Play again? (y/n) ")
    if choice == "n":
        break

Totalling and counting

Totalling adds each value to a running total; counting adds 1 each time something happens. Both must be initialised to 0 before the loop.

total = 0
count = 0
number = int(input())
while number != -1:
    total = total + number
    count = count + 1
    number = int(input())
print(total, count)

With inputs 4, 7, 2, -1 this prints 13 3 (−1 is a rogue value that stops the loop and is not counted).

String handling

The first character is at position 0.

MethodPurposes = "the cat sat"
len(s)Number of characters11
s.find("cat")Position of first match (−1 if absent)4
s.count("at")How many times a substring appears2
s.upper()Uppercase"THE CAT SAT"
s.lower()Lowercase"the cat sat"
s.title()First letter of each word capital"The Cat Sat"
s.replace("cat", "dog")Replace a substring"the dog sat"
+Concatenation (join)"the" + "!" → "the!"

String methods return a new string — store it: s = s.upper(). Slicing s[0:3] gives "the".

Exam tips

  • When writing code, always initialise totals and counters before the loop and cast input() to int or float when doing arithmetic.
  • Choose the right loop and say why: for = known number of repetitions; while = repeat until a condition changes; while True … break = must run at least once.
  • Remember string positions start at 0 and find() returns -1 when the substring is missing.
  • Use meaningful variable names in every answer — they are credited in the 15-mark scenario question.
  • Constants in CAPITALS (e.g. MAX_SIZE) show the examiner you know the convention.

Mistakes that lose marks

  • Forgetting that input() returns a string, so '5' + '3' gives '53'.
  • Using = (assignment) instead of == (comparison) in a condition.
  • Thinking range(1, 10) includes 10.
  • Calling s.upper() without storing the result — the original string is unchanged.
  • Missing the colon or the indentation after if, elif, else, for, while, match and case.

8.2Programming operators

Operators do the work in expressions: arithmetic operators calculate, relational operators compare and give True or False, and logical operators combine conditions.

Arithmetic operators

OperatorMeaningExampleResult
+Addition7 + 29
-Subtraction7 - 25
*Multiplication7 * 214
/Float division7 / 23.5
//Floor division (whole part)7 // 23
%Modulus (remainder)7 % 21
**Raise to the power2 ** 38

/ always gives a float (8 / 2 is 4.0). % is used to test even numbers (n % 2 == 0) and divisibility; // with % splits minutes into hours and minutes:

minutes = 135
print(minutes // 60, "h", minutes % 60, "min")

Output: 2 h 15 min. Brackets first, then *, then / // %, then + -.

Relational operators

They compare two values and give a Boolean (True/False):

== equal to!= not equal to< less than<= less than or equal to> greater than>= greater than or equal to
age = 16
print(age >= 16, age != 16, age < 13)

Output: True False False.

Logical operators

  • and — True only if both conditions are True.
  • or — True if at least one is True.
  • not — reverses a Boolean.
mark = 85
attendance = 92
if mark >= 80 and attendance >= 90:
    print("Merit award")
if mark < 0 or mark > 100:
    print("Invalid")
finished = False
if not finished:
    print("Keep going")

Output: Merit award then Keep going. Each side of and/or must be a complete comparison: mark < 0 or mark > 100, never mark < 0 or > 100.

Exam tips

  • Know the difference between / (gives a float), // (whole-number part) and % (remainder) — trace questions test it.
  • Use and for 'between' checks (x >= 1 and x <= 10) and or for 'outside' checks (x < 1 or x > 10).
  • When asked for the result of an expression, show the type: 10 / 2 is 5.0, not 5.

Mistakes that lose marks

  • Writing = instead of == in a comparison.
  • Writing incomplete conditions like if x == 1 or 2 (always True).
  • Confusing % (remainder) with percentage.
  • Using ^ for a power — Python's power operator is **.

Infographics2download any diagram as PNG or SVG

Python basics: data types, casting, input and operatorsinput() always returns a string, so cast it before doing arithmetic. Constants are written in CAPITALSby convention.TypeExampleCast to itint42int("42")float3.5float("3.5")str"Ali"str(42)boolTruebool(1)Input and outputMAX_MARK = 100name = input("Name: ")mark = int(input("Mark: "))print(name, "scored", mark)print("Percent:", mark / MAX_MARK * 100)ArithmeticOperatorExampleResult+ - *7 * 214/7 / 23.5// (floor div)7 // 23% (modulus)7 % 21** (power)2 ** 38Compare, combine, strings== != < <= > >= and or nots = "Python"len(s) → 6 s.upper() → "PYTHON"s[0:3] → "Pyt" s + "!" → "Python!"= assigns a value; == compares two values. A comparison gives a bool: True or False.cswithzak.com

Python basics: types, casting, operators

O Level
Python selection and iterationIndentation shows which lines belong to an if, case or loop. Count-controlled = for;condition-controlled = while.Selectionmark = int(input("Mark: "))if mark >= 70: grade = "A"elif mark >= 50: grade = "B"else: grade = "U"match grade: case "A": print("Well done") case _: print("Keep going")Iteration, totalling and countingtotal = 0count = 0for i in range(5): # 5 times n = int(input()) total = total + n if n > 50: count = count + 1print(total, count)answer = ""while answer != "yes": answer = input("Ready? ")range(5) gives 0–4; range(1, 6) gives 1–5. case _ matches anything left (like else). break leaves a loop early.cswithzak.com

Python selection and iteration

O Level

Python for this topic16Python 3.10+, the only language on Paper 2 — runs in your browser

Key terms17use these exact words in the exam

variableconstantcastingintfloatstrboolelifmatch-casefor loopwhile loopbreaktotallingcountingconcatenationfloor divisionmodulus

Test yourself

Check you know the 2029–2031 content

Written for the new syllabus only: every card and question traces to a learning objective above. Rounds are random, and marks earn XP on your dashboard.

4 decks · 46 cards · 20 quiz questions.

From the current course

Most of this topic is taught in the 2026–2028 course today. Its notes and past-paper questions still help — skip anything the 2029–2031 syllabus removed (see the notes above), and remember those past papers answer in pseudocode: write Python instead.

Enroll nowOnline classes