Python Foundations

Selection & Operators

Input, output, selection (IF/CASE) and operators — print(), input(), f-strings, type conversion, if / if-else / if-elif-else, nested if, logical operators, and the // (DIV) and % (MOD) arithmetic operators. The decision-making building blocks every Paper 4 program needs.

2.1 Data Types Recap

Before you can write a real Paper 4 program, you need the building blocks: storing information, receiving it from a user, and making decisions. Python follows the same logic as pseudocode — the only difference is exact syntax.

Python has five data types you need for this syllabus:

TypeKeywordExampleUse
Integerintage = 17Whole numbers
Realfloatprice = 3.99Decimal numbers
Stringstrname = "Alice"Text
BooleanboolisLoggedIn = TrueTrue / False
NoneNoneTyperesult = NonePlaceholder (no value yet)
Exam tip:
  • Always choose the most specific type.
  • Use int (not float) for whole numbers, and bool (not int) for True/False.
  • Using the wrong type does not always crash, but it loses the mark for that variable.
# Type casting — converting between types
x = "42"          # str — cannot do arithmetic
y = int(x)        # now y is the integer 42
z = float(x)      # z is 42.0

int("15")     # -> 15
float("3.14") # -> 3.14
str(100)      # -> "100"
bool(0)       # -> False
bool(1)       # -> True
Your Turn — Identifying and declaring variables with correct types [3 marks]
A program stores a student's name, exam score, and whether they passed. Write a Python snippet that declares appropriate variables and prints a message showing all three.
Hint:
  • Name is text → str
  • Exam score is a whole number → int
  • Passed/failed is yes/no → bool
Your Turn [4 marks]
A program stores a product name, its price, the quantity in stock, and whether it is currently on sale. Declare appropriate variables with realistic values and print a single line displaying all four.
Hint:
  • Price has a decimal point → float
  • Quantity is a whole number → int
  • On sale is yes/no → bool

2.2 Input & Output

Almost every Paper 4 program starts by reading values from the user and ends by printing results. Forgetting to convert input() is the single most common mistake in Paper 4.

Output — print() and f-strings

# Basic print
print("Hello, World!")
print(42)

# f-string — variables go inside { }
name = "Omar"
age = 16
print(f"Name: {name}, Age: {age}")
Task
Write a Python program that stores a city name and its population as variables, then prints: City: [name], Population: [number] Use an f-string for the output.

Input — input() always returns a string

# input() always returns str — convert immediately if you need arithmetic
name = input("Enter your name: ")          # str, no conversion
age = int(input("Enter your age: "))        # convert to int
price = float(input("Enter price: "))       # convert to float
Task
Write the correct input() statement for each: - A student's name (used as a label) - Their year of birth (used in a calculation) - Their average mark (can have decimals)
Key rule — input() always returns str:
  • input() returns a string even if the user types a number.
  • "5" + "3" is "53" (concatenation), not 8.
  • Always wrap with int() or float() when you need arithmetic.
Your Turn — Input with type conversion and formatted output [4 marks]
Write a Python program that asks the user for their name and year of birth, then calculates and outputs their age in 2025.
Hint:
  • Name is str (no conversion needed)
  • Year of birth must be int (to subtract from 2025)
Your Turn [4 marks]
Write a Python program that asks for the price of an item (float) and the quantity to buy (int). Calculate the total cost and output: Total cost: [amount]
Hint:
  • price → float
  • quantity → int
Exam tip:
  • The single most common Paper 4 mistake is forgetting to convert input().
  • If your program does arithmetic with user input and you have not used int() or float(), the marker will not award method marks for the calculation — even if the logic is correct.

Lab Tasks — Practice I/O

Lab Task — Circle Area
Ask for the radius of a circle (float). Output the area. Use 3.14159 for pi.
Lab Task — Celsius to Fahrenheit
Ask for a temperature in Celsius. Convert to Fahrenheit: F = C * 9/5 + 32
Lab Task — Full Name
Ask for a first name and last name separately. Print: Full name: [FirstName] [LastName]

2.3 The if Statement Family

Conditional statements are how a program makes decisions. In Paper 4 you will almost always need at least one if. Cambridge marks carefully: correct indentation and the right branch structure are both required.

if — one branch

# Pseudocode: IF age >= 18 THEN ... ENDIF
age = int(input("Enter your age: "))
if age >= 18:
    print("You are eligible to vote.")

if-else — two branches

age = int(input("Enter your age: "))
if age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not old enough to vote.")
Task
Write a program that asks the user for a number. If the number is positive, print "The number is positive."
Task
Write a program that asks the user for a number. If the number is positive, print "Positive." Otherwise, print "Not positive."
Key rule — Python indentation:
  • The code block inside an if must be indented by 4 spaces.
  • This is how Python knows what belongs inside the block — there is no ENDIF keyword.
  • Forget the indentation and Python raises an IndentationError.
Your Turn — if-else with a real scenario [4 marks]
A shop offers a 10% discount if the total bill is £50 or more. Write a Python program that reads the bill amount and outputs the final amount to pay.
Your Turn [4 marks]
A password system accepts a password only if its length is 8 or more characters. Read a password and print "Access granted" or "Password too short."
Hint:
  • Use len() to find the length of a string
  • len("hello") returns 5

if-elif-else — more than two outcomes

Use elif when there are more than two possible outcomes. Python tests conditions top to bottom and runs the first branch that is True — then skips the rest.

marks = int(input("Enter marks: "))
if marks >= 90:
    print("Grade: A*")
elif marks >= 80:
    print("Grade: A")
elif marks >= 70:
    print("Grade: B")
elif marks >= 60:
    print("Grade: C")
else:
    print("Grade: F")
Key rule — order matters in elif:
  • Python checks conditions from top to bottom and stops at the first True one.
  • Always order from most restrictive to least restrictive (e.g. highest marks to lowest).
  • Getting the order wrong produces correct-looking code that gives wrong output.
Task
Write a program that classifies a temperature (float): - Below 0 -> "Freezing" - 0 to 10 -> "Cold" - 11 to 20 -> "Mild" - 21 to 30 -> "Warm" - Above 30 -> "Hot"
Your Turn — if-elif-else with multiple branches [5 marks]
A theme park charges entry fees by age: Under 5 — free; 5 to 12 — £8; 13 to 59 — £15; 60 and over — £10. Write the Python program.
Your Turn [5 marks]
A bus fare system charges by age: Under 5 — free; 5 to 15 — £1.20; 16 to 59 — £2.50; 60 and over — £1.00. Read an age and output the correct fare.
Exam tip:
  • When Cambridge asks you to "write a conditional statement", always include every branch — do not leave out the else unless the question specifically requires only an if.
  • Missing a branch loses a mark.

2.4 Nested if & Logical Operators

A nested if is an if placed inside another if block. Use nesting when you need to check a second condition that only makes sense once the first is already True.

age = int(input("Enter age: "))
hasLicense = input("Have a license? (yes/no): ")

if age >= 17:
    if hasLicense == "yes":
        print("You can drive.")
    else:
        print("You need a license to drive.")
else:
    print("You are not old enough to drive.")
Task
Write a program that checks if a user can enter a competition: they must be 16 or over. If they are 16+, also check if they are a member — if yes, print "You can enter."; if no, print "Members only." Under 16: print "Too young."
Your Turn — Nested if [5 marks]
A cinema sells tickets to 18+ films only to adults. If an adult has a student card, the ticket is £7; otherwise £12. Under 18s cannot see the film. Write the program.
Your Turn [5 marks]
A gym requires users to be 16 or over. If they are 16+, check for a referral code: with one, charge £20/month; without, £30/month. Under 16s get a message that they are ineligible.

Logical operators — and / or / not

Combine multiple conditions using these three operators:

OperatorMeaningExample
andAll conditions must be Trueage >= 18 and isRegistered
orAt least one condition must be TruehasTicket or knowsHost
notNegates the conditionnot isRaining
Task — and
Write a program that asks the user for two grades. If both grades are above 50, print "You passed."
Task — or
Write a program that checks if the user has either a membership card or a discount code. If they have any one, print "You get a discount." Otherwise, print "No discount for you."
Task — not
Write a program that checks if it is not raining and prints "You can go for a walk." Otherwise, print "Take an umbrella."

2.5 Operators: //, %, and the Rest

Cambridge Paper 4 specifically tests // and % because they map directly to DIV and MOD in pseudocode.

Arithmetic operators

OperatorNameExampleResultPseudocode
+Addition7 + 310+
-Subtraction7 - 34-
*Multiplication7 * 321*
/Division (float)7 / 23.5/
//Integer division7 // 23DIV
%Modulus (remainder)7 % 21MOD
**Exponentiation2 ** 8256^

Comparison & logical operators

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than7 > 3True
<Less than2 < 1False
>=Greater or equal5 >= 5True
<=Less or equal4 <= 3False
andBoth True5>3 and 2<4True
orAt least one True5>10 or 2<4True
notNegatesnot (5>3)False
Your Turn — Using // and % (integer division and modulus) [4 marks]
A program receives a number of seconds as an integer. Calculate and output the equivalent whole minutes and remaining seconds. For example, 145 -> 2 minutes and 25 seconds.
Your Turn [4 marks]
A program receives a total number of minutes. Calculate and output the number of whole hours and remaining minutes. For example, 145 minutes -> 2 hours and 25 minutes.
Task
Write a program that reads a total number of hours (int) and outputs the number of whole days and remaining hours. Example: 50 hours -> 2 days and 2 hours
Exam tip: If a Paper 4 question shows pseudocode with DIV or MOD, always translate those to // and % in Python — never use int(a/b) as a substitute.

2.6 Exam Focus & Lab Tasks

Common mistakes that lose marks

MistakeWhat happensFix
Forgetting int() / float() around input()TypeError or wrong string arithmeticAlways convert numeric inputs immediately
= instead of == in a conditionSyntaxError or assignment instead of comparisonif x == 5: not if x = 5:
Wrong indentationIndentationError — program crashes4 spaces per level; be consistent
/ when integer result is neededGets a float (3.0) instead of int (3)// for integer division — maps to DIV
Wrong order of elif branchesFirst True branch runs, wrong outputOrder conditions carefully; test boundary values
Missing the else branchSome inputs produce no outputAlways include else unless question says otherwise

Exam-style Lab Tasks

Lab Task — 1 — FizzBuzz
Ask for an integer. If divisible by both 3 and 5, print FizzBuzz. If divisible by 3 only, print Fizz. If divisible by 5 only, print Buzz. Otherwise print the number itself.
Lab Task — 2 — BMI Calculator
Ask for weight in kg (float) and height in metres (float). Calculate BMI: bmi = weight / (height ** 2). Classify: <18.5 -> Underweight; 18.5-24.9 -> Normal; 25-29.9 -> Overweight; >=30 -> Obese. Print BMI (2 d.p.) and category.
Lab Task — 3 — Bank Account Login
Store correct username "admin" and PIN 1234. Ask for username and PIN from user. If both match -> "Access granted. Welcome, [username]." If username matches but PIN does not -> "Incorrect PIN." If username does not match -> "User not found."
Lab Task — 4 — Time Converter
Ask for total minutes (int). Convert to hours and remaining minutes using // and %. Output: [total] minutes = [hours] hours and [mins] minutes. Extension: if total >= 1440, also show days, hours, and minutes.
Lab Task — 5 — Grade Calculator
Ask for three subject marks (int): Maths, English, Science. Calculate the average. Classify: >=90 Outstanding; >=75 Very Good; >=60 Good; >=40 Satisfactory; else Needs Improvement. Print: Average: [avg] - Classification: [class]. Extension: flag if any single subject is below 40.

Key Points Summary

Python has 5 data types: int, float, str, bool, NoneType — choose the most specific.
input() ALWAYS returns a str — wrap with int() or float() for arithmetic.
f-strings (f"...{var}...") format output with variables in { }.
if / if-else / if-elif-else — Python uses a colon and 4-space indentation (no ENDIF).
In if-elif-else, only the FIRST True branch runs — order from most to least restrictive.
Nested if is for dependent conditions; if-elif-else is for independent branches.
Logical operators are words: and, or, not (not &&, ||, !).
// is integer division (pseudocode DIV); % is modulus (pseudocode MOD).
== is comparison; = is assignment — never use = inside an if.
Always include the else branch in exam answers unless told otherwise.

2.7 Practice Tasks

Fifteen exam-style tasks. Click Hint for bullet-point guidance, then Help to reveal a worked Python solution.

1Practice Task — if / elif / else [2 marks]
Given score = 55, write if/elif/else that prints "Pass" for 50+, "Resit" for 30-49, otherwise "Fail".
2Practice Task — Comparison operators [2 marks]
List the six Python comparison operators and state what each one returns (True/False).
3Practice Task — Logical operators and / or / not [3 marks]
Write an if that prints "Allowed" when age is 16+ AND has_ticket is True, otherwise "No entry".
4Practice Task — Nested if [4 marks]
Ask the user for age. If 18+, ask "Do you have a license? (y/n)". If y, print "Drive". If 18+ but n, print "No license". Under 18 print "Too young".
5Practice Task — Range checks [4 marks]
Read a mark from the user. Print "Valid" only when 0 &lt;= mark &lt;= 100, otherwise "Out of range".
6Practice Task — Grade boundaries [5 marks]
Given mark (0-100), print: A (90+), B (80-89), C (70-79), D (60-69), F (below 60). Use if/elif/else.
7Practice Task — Leap year [6 marks]
A year is a leap year if divisible by 4 AND (NOT divisible by 100 OR divisible by 400). Write an if/else that prints "Leap" or "Not leap".
8Practice Task — Largest of three [4 marks]
Given a, b, c (all distinct), print the largest using only if/elif/else — no max() function.
9Practice Task — BMI calculator [6 marks]
Read weight (kg, float) and height (m, float). Compute BMI = weight / (height**2). Print: Underweight (&lt;18.5), Normal (18.5-24.9), Overweight (25-29.9), Obese (30+). Round BMI to 1 decimal in output.
10Practice Task — Discount calculator [5 marks]
Read price and qty. Compute subtotal = price * qty. Apply 10% discount if subtotal &gt; 100, 5% if subtotal &gt; 50, otherwise 0%. Print final total to 2 decimals.
11Practice Task — Eligibility checker [4 marks]
A voter is eligible if age &gt;= 18 AND (citizenship == "citizen" OR has_residency == True). Write the if/else and print "Eligible" / "Not eligible".
12Practice Task — Even or odd with MOD [2 marks]
Read an integer and print "Even" or "Odd" using the % operator.
13Practice Task — Truth tables [3 marks]
Write out the truth table for the logical AND operator. Show all four combinations of A and B and the result of A and B.
14Practice Task — Operator precedence [4 marks]
Predict the value of: (a) not True or False, (b) True and False or True, (c) 5 &gt; 3 and 2 == 2. Explain why.
15Practice Task — Exam-style: full selection question [8 marks]
A theme park ride requires: age &gt;= 12 AND height &gt;= 120 cm. (a) Read age and height [2]. (b) Print "Ride allowed" if both pass [2]. (c) Otherwise, print a SPECIFIC reason — "Too young" if age failed, "Too short" if height failed, "Both" if both failed [4].

Question Bank

Answer all questions, then press Submit Quiz to see your score.

0/12 answered

Question 1Multiple Choice

Which data type is most appropriate for storing a temperature reading of 36.7?

Question 2True / False

input() returns a string even when the user types a number.

Question 3Multiple Choice

What is the output of: print(f"Total: {5 + 3}")

Question 4Multiple Choice

Which line correctly reads a decimal price from the user for arithmetic?

Question 5True / False

In an if-elif-else chain, Python runs the first branch whose condition is True and then skips the rest.

Question 6Multiple Choice

Which Python operator gives the remainder of 17 divided by 5?

Question 7Multiple Choice

Which is the correct way to check if two values are equal in an if condition?

Question 8True / False

The condition `age >= 18 and isRegistered` is True only if both parts are True.

Question 9Multiple Choice

What is 7 // 2 in Python?

Question 10Multiple Choice

A nested if is best used when:

Question 11True / False

Python uses indentation (4 spaces) instead of keywords like ENDIF to mark the end of an if block.

Question 12Multiple Choice

Which common Paper 4 mistake is caused by using / when an integer result is needed?

Answer all 12 questions to enable submission.