GCSE
AQA Computer Science
8525
Python 2
Python 1
• Introduction • If Statements (Selection)
• Basic Syntax and Variables • Comparison Operations
• Data Types • Logical Operations
• Basic Output and Input • Iteration (Loops)
• Arithmetic Operations
• String Operations
Python 2
• Lists (Arrays) • Random Numbers
• 2D Lists (2D Arrays) • Common Exam Algorithms
• Functions (Subroutines) • Records (Dictionaries)
• File Handling
• String Manipulation
Python 3
• Common Mistakes to Avoid
• Key Things to Remember
• Quick Reference for Common Tasks
• Practice Questions
Python 1
Review
Question 1: Input and Data Type Conversion
A program needs to calculate the total cost of items in a shopping basket. The user
enters the number of items and the price per item.
Write Python code that:
• Asks the user to input the number of items
• Asks the user to input the price per item
• Calculates and displays the total cost
Make sure your code handles the input correctly for calculations.
number_of_items = int(input("Enter the number of items: "))
price_per_item = float(input("Enter the price per item: "))
total_cost = number_of_items * price_per_item
print("Total cost:", total_cost)
Key points:
• int() conversion for number of items (whole number)
• float() conversion for price (may have decimals)
• Without conversion, input() returns strings and calculation won't work
correctly
Question 2: Selection with Logical Operations
A cinema needs to check if customers are eligible for a student discount. To qualify, a
customer must be between 16 and 25 years old (inclusive) AND have a valid student
ID.
Write Python code that:
• Asks for the customer's age
• Asks if they have a student ID (yes/no)
• Displays "Discount approved" if they meet BOTH requirements
• Displays "No discount available" if they don't meet the requirements
Option 1
age = int(input("Enter your age: "))
student_id = input("Do you have a student ID? (yes/no): ")
if age >= 16 and age <= 25 and student_id == "yes":
print("Discount approved")
else:
print("No discount available")
Key points:
• Use and operator - ALL conditions must be true
• == for comparison (not =)
• Check age range with two conditions
Option 2
age = int(input("Enter your age: "))
student_id = input("Do you have a student ID? (yes/no): ")
if age >= 16 and age <= 25 and student_id.lower() == "yes":
print("Discount approved")
else:
print("No discount available")
Key points:
Optional: .lower() makes input checking more flexible
Question 3: Iteration with Validation
A password system requires users to enter a password that is at least 8 characters
long. The program should keep asking until the user enters a valid password.
Write Python code that:
• Repeatedly asks the user to enter a password
• Checks if the password is at least 8 characters long
• Keeps asking until a valid password is entered
• Displays "Password accepted" when a valid password is entered
Decide whether to use a FOR loop or WHILE loop and explain why.
Option 1
password = ""
while len(password) < 8:
password = input("Enter a password (at least 8 characters): ")
print("Password accepted")
Option 2
password = input("Enter a password (at least 8 characters): ")
while len(password) < 8:
print("Password too short!")
password = input("Enter a password (at least 8 characters): ")
print("Password accepted")
Key points:
• Use a while loop (not FOR) because we don't know how many attempts the user
will need
• len() function checks string length
• Loop continues until condition is false (password is 8+ characters)
• Must update the password variable inside the loop or it will run forever
• Colon : after while statement
• Indentation for code inside the loop
Why WHILE not FOR:
• We don't know in advance how many times the user will enter an invalid
password
• The loop is condition-based (keep going until valid)
• FOR loops are for known repetitions (e.g., "ask 5 times")
Question 4: String Operations and Concatenation
A school needs to generate student ID numbers automatically. The student ID format
is:
• First 3 letters of the first name (uppercase)
• First 3 letters of the surname (uppercase)
• A 2-digit number representing the length of the surname
• Eg: First name: "Ali", Surname: "Patel" → Student ID: "ALIPAT05"
Write Python code that:
• Asks the user to input their first name
• Asks the user to input their surname
• Generates and displays their student ID in the correct format
Hints:
• Use string slicing to get the first 3 letters
• Use .upper() to convert to uppercase
• Use len() to find the length of the surname
• Use str() to convert numbers to strings for joining
• Consider what happens if the number is less than 10 (single digit)
Option 1:
first_name = input("Enter your first name: ")
surname = input("Enter your surname: ")
first_part = first_name[0:3].upper() # Extract first 3 letters and convert to uppercase
surname_part = surname[0:3].upper()
surname_length = len(surname) # Calculate surname length
if surname_length < 10:
length_part = "0" + str(surname_length) # Convert to string and format as 2 digits
else:
length_part = str(surname_length)
student_id = first_part + surname_part + length_part # Combine all parts
print("Your student ID is:", student_id)
Option 2:
first_name = input("Enter your first name: ")
surname = input("Enter your surname: ")
student_id = first_name[0:3].upper() + surname[0:3].upper() +
str(len(surname)).zfill(2)
print("Your student ID is:", student_id)
Key points:
• String slicing [0:3] gets first 3 characters
• .upper() converts to uppercase
• len() gets the length of the surname
• str() converts the number to a string for concatenation
• Use "0" + str(surname_length) or .zfill(2) to ensure 2 digits (adds leading zero if
needed)
• + operator concatenates (joins) strings
• Order of operations matters when building the ID
Python 2
Tuple vs Variable
Variable
• A variable is a name (an identifier) that refers to a value stored in the computer's
memory.
• They are not a data type themselves; rather, they are labels that can point to any
type of Python object, such as integers, strings, lists, or tuples.
Role: To store and manage data in a program.
Mutability of reference: A variable can be reassigned to point to a different value
at any time.
Syntax: Defined using square brackets [] and commas ,
Tuple
• A tuple is a specific, built-in data structure used to store a collection of items.
• Key characteristics of a tuple are that it is ordered (items have a defined
sequence) and, most importantly, immutable.
• This means that once a tuple is created, its contents cannot be changed (you
cannot add, remove, or modify elements).
Role: To store a fixed collection of related data, often used for data that should not
change (e.g., coordinates, database records).
Mutability of contents: Immutable (cannot be changed in place).
Syntax: Defined using round brackets () and commas ,
Lists (Arrays)
This may be used for:
• Storing multiple items (scores, names, prices)
• Processing collections of data.
- Creating and Accessing Lists -
Creating Lists
scores = [85, 92, 78, 95, 88] # [ ] Can alter contents / order
( ) Tuple – data is fixed and cannot be changed
names = ["Alice", "Bob", "Charlie"]
empty_list = []
Accessing Lists
first_score = scores[0] # 85 [ ] for position
last_score = scores[-1] # 88
Length of List
num_scores = len(scores) # 5 len() is a function (instruction) not a
variable
Critical punctuation:
• Square brackets [] for creating and accessing lists
• Commas between items: [1, 2, 3] not [1 2 3]
• Index starts at 0: first item is [0] not [1]
• Negative index counts from end: [-1] is last item
Common mistakes:
• Trying to access scores[5] when list has 5 items (0-4 only) - causes error!
• Forgetting list is zero-indexed in exam questions
- Modifying Lists -
scores = [85, 92, 78]
[Link](95) # [85, 92, 78, 95] Add to end
[Link](1, 90) # [85, 90, 92, 78, 95] Insert at position
[Link](78) # [85, 90, 92, 95] Remove item
del scores[0] # [90, 92, 95] Remove by index
scores[0] = 100 # [100, 90, 92, 95] Update a specific position
Punctuation notes:
• Dot notation for methods: .append(), .remove()
• Parentheses with the value: .append(95) not .append 95
• del is a keyword, doesn't use dot: del scores[0]
- Looping through Lists -
scores = [85, 92, 78, 95]
Method 1 - direct access (preferred)
for score in scores: #This loop takes each item (1 by 1) from the scores list,
and temporarily assigns it to the variable score
print(score) #Each number on a new line
Method 2 - using index (when you need position)
for i in range(len(scores)): # len(scores) gets total number of items in list
range(len(scores)) creates a sequence of numbers
(0,1,2,3)
The loop assigns each number from the sequence
(0,1,2,3) to the variable i
print(scores[i]) #Uses the index i to access the element at that position
in the list.
Eg: scores[0] is 85 and scores[1] is 92
Each number on a new line
Punctuation notes:
• Colon : at the end of the for line - NEVER forget this!
• Indentation (4 spaces or tab) for code inside the if - Python requires this
When to use each:
• Method 1: When you just need the values (displaying, calculating)
• Method 2: When you need the position number (updating, comparing with
another list)
Common exam tasks:
• Calculate average: loop through, add to total, divide by length
• Find maximum: loop through, compare each with current maximum
• Count occurrences: loop through, count how many match condition
2D Lists (2D Arrays)
This may be used for:
• Grids
• Tables
• Seating plans
• Game boards
• Timetables
• Spreadsheet-like data
Create a 2D list (like a grid/table)
grid = [ # grid = [] creates a table
[1, 2, 3], # [] opens and closes each row
[4, 5, 6], # commas , are used to separate rows and columns
[7, 8, 9]
] # ends the table
Access items (row, then column)
value = grid[0][1] # 2 (first row, second column)
value = grid[2][0] # 7 (third row, first column)
Loop through 2D list (Nested)
for row in grid:
for item in row:
print(item, end=" ") # Prints the element followed by a space
print() # New line after each row
Critical punctuation:
• Square brackets within square brackets: [[1,2], [3,4]]
• Two sets of brackets to access: grid[row][column]
• Both indices start at 0
Common exam uses:
• Tic-tac-toe board: board[row][col]
• Seating plan: seats[row][seat_number]
• Test scores: scores[student][test_number]
Nested loop pattern:
• Outer loop goes through rows
• Inner loop goes through each element in that row
• This processes EVERY item in the grid
Functions (Subroutines)
This may be used for:
• Reusing code
• Organizing programs,
• Breaking big tasks into smaller ones
- Defining and Calling Functions -
Function without parameters
def greet(): #def greet() defines the instruction greet
print("Hello!") #indent shows it’s inside the greet function
greet() # Calls (Runs) the function. Output is Hello!
Function with parameters
def greet_person(name):
print("Hello", name)
greet_person("Alice") #Output is Hello Alice
Function with multiple parameters
def add_numbers(num1, num2):
total = num1 + num2
print(total)
add_numbers(5, 3)
Critical punctuation:
• def keyword to define function
• Colon : after function header
• Parentheses () for parameters (even if empty)
• Indentation for function body
• Function names follow same rules as variables (no spaces, lowercase)
Parts of a function:
def calculate_total(price, quantity): # Header
total = price * quantity # Body (indented)
return total # Return statement
result = calculate_total(10, 3) # Runs function using Arguments: 10
and 3
Parameter: variable in the definition (price, quantity)
Argument: actual value when calling (10, 3)
- Functions that Return Values -
When to use return:
• When you need to get a value BACK from the function
• For calculations that you'll use elsewhere
• Return ends the function immediately
def calculate_area(length, width):
area = length * width
return area
result = calculate_area(5, 3)
print(result) # 15
Multiple return values
def get_stats(numbers): #defines function with one argument
total = sum(numbers) #sum() functions adds all elements
average = total / len(numbers) #calculates average; result is a float
return total, average #returns both total and average (tuple)
t, a = get_stats([10, 20, 30]) #tuple is unpacked t 1st value a 2nd value
- With vs Without return -
Without return (just does something)
def display_message(text):
print(text)
display_message("Hello") # Prints but gives back nothing
With return (gives back a value)
def double_number(num):
return num * 2
result = double_number(5) # result = 10
Common exam uses:
• Validation function:
• def is_valid_age(age):
• returns True/False
• Calculation function:
• def calculate_average(numbers):
• returns the average
• Search function:
• def find_student(name):
• returns position or -1
Common mistakes:
• Forgetting parentheses when calling: greet ✗ should be greet() ✓
• Returning without capturing: calculate_area(5, 3) ✗ should be result =
calculate_area(5, 3) ✓
• Forgetting to indent function body