Teaching Resource

Mastering the Programming Language Subset

A comprehensive guide to help students effectively use the PLS document during Edexcel GCSE Computer Science Paper 2 examinations.

June 2024 June 2023 June 2022 1CP2/02
01

What is the PLS?

The Programming Language Subset (PLS) is a reference document provided during the Paper 2 exam that specifies exactly which Python 3 features students need to know. It's essentially a cheat sheet that students can use throughout the 2-hour practical exam.

βœ“
What It Covers
  • Data types and conversion functions
  • All operators (arithmetic, relational, logical)
  • Selection and iteration syntax
  • File handling operations
  • String manipulation methods
  • Random, math, and time libraries
  • Turtle graphics commands
⚠
What It Doesn't Cover
  • When to use specific constructs
  • Problem-solving strategies
  • Algorithm design
  • How to debug logic errors
  • How to interpret test data
πŸ’‘ Key Insight

The PLS confirms syntax, not logic. Students still need to understand what they're trying to achieveβ€”the PLS just helps them write it correctly.

02

Phase 1: Familiarisation

Know the Layout, Not the Content

Students shouldn't memorise the PLS but should know where things are. The goal is to locate any syntax within 20 seconds.

Section Page Key Contents
Data types & conversion 5 int(), float(), str(), bool()
Operators 6 //, %, ==, and, or
Selection & Iteration 7 if/elif/else, while, for
File operations 8 open(), read(), write(), close()
String methods 11 split(), strip(), upper(), isdigit()
Random library 13 random.randint(a, b)
Math library 13 math.ceil(), math.floor(), math.pi

Pattern Recognition

When students see certain words in questions, they should instinctively think of specific PLS sections:

Question Contains... Check PLS For... Page
"random number" random.randint(a, b) 13
"first two letters" String slicing myName[0:2] 12
"round up" / "whole bags" math.ceil() 13
"add to the end" list.append() 10
"split by comma" string.split(",") 11
"ASCII value" ord() and chr() 9
03

Debugging Examples

πŸ”§
Rainbow Program - Fixing Multiple Errors
June 2024, Question 1 (10 marks)

A program displays rainbow colours based on wavelength. Students must fix 10 different errors.

Error Type Original Code PLS Reference Fix
Syntax 597", 622] Page 5 597, 622]
NameError found = false Page 5 found = False
Syntax wavelength = 0123 Page 5 wavelength = 123
Syntax int(input("...") Page 8-9 int(input("..."))
NameError color = rainbow[index] Check spelling colour = rainbow[index]
ValueError print(int(colour)) Page 5 print(colour)
Logic if (x < 380) and (x > 622) Page 6 if (x < 380) or (x > 622)
πŸ’‘ Teaching Point

The logic error with and vs or is common. A number cannot be both less than 380 AND greater than 622 simultaneously. The PLS page 6 shows that or means "either side must be true".

πŸƒ
Exercise Routine - Import and Loop Errors
June 2023, Question 2 (8 marks)

A program selects random exercises from an array. Multiple syntax and logic errors need fixing.

Error Type Original Code PLS Reference Fix
Syntax import randum Page 13 import random
Syntax for exercise in exerciseTable Page 7 for exercise in exerciseTable:
IndexError exerciseTable[index + 1] Page 5 exerciseTable[index]
Logic range(numExercises - 1) Page 9 range(numExercises)

Completing the Random Number Line

The question asks to complete: index = random.

Check PLS page 13:

# PLS shows: random.randint(<a>, <b>)
# Returns random integer where a <= X <= b
# Array has 5 elements, indices 0-4

index = random.randint(0, 4)
πŸ’‘ Critical Understanding

PLS page 9 states that range() generates numbers "up to, but not including" the stop value. So range(5) gives 0,1,2,3,4 (five iterations). Using range(numExercises - 1) would give one fewer iteration than needed.

πŸ”€
Number to Letter Conversion
June 2022, Question 1 (10 marks)

Convert numbers 5-30 to letters A-Z using ASCII. Adding 60 to a number gives the ASCII code for the corresponding uppercase letter.

Task-by-Task Solution

# Task 1: Create integer variable (PLS page 5)
num = 0

# Task 2: Take input and convert to integer
# PLS page 5: int() and page 8: input()
num = int(input("Enter a number: "))

# Task 3: Check between 5 and 30
# PLS page 6: >= and <= operators, "and" operator
if num >= 5 and num <= 30:
    # Task 4: Add 60 and assign
    decimalCode = num + 60
    
    # Task 5: Join strings (PLS page 12: use +)
    letter = chr(decimalCode)
    message = str(num) + " is equal to " + letter
    print(message)
else:
    # Task 6: Display error message
    print("Invalid input")
04

File Handling Examples

πŸ“
Coffee Consumption CSV Writer
June 2022, Question 5 (15 marks)

Write coffee consumption data to a CSV file with 7 values per line (one week per line).

PLS Sections Needed

Open for Writing
open(filename, "w") Page 8
Write String
file.write(string) Page 8
Close File
file.close() Page 8
# Open file for writing - PLS page 8
outputFile = open("Q05_OUTPUT.TXT", "w")

# Process in groups of 7
for i in range(0, len(coffeeData), 7):
    # Build CSV line
    line = ""
    for j in range(7):
        line = line + str(coffeeData[i + j])
        if j < 6:
            line = line + ","
    
    # Add newline and write - PLS page 15 shows "\n"
    outputFile.write(line + "\n")

# Close file - PLS page 8
outputFile.close()
πŸ„
Cow Data Processing with Key Generation
June 2024, Question 6 (15 marks)

Read cow data from CSV, create unique keys, and store records in a table.

Key format: first 2 letters of breed + (tag Γ· 100) + first 2 letters of name

PLS Sections Needed

Task PLS Reference Syntax
Open file for reading Page 8 open(filename, "r")
Split CSV line Page 11 string.split(",")
Get first 2 characters Page 12 myName[0:2]
Integer division Page 6 //
# Open file - PLS page 8
cowFile = open("Cows.txt", "r")
cowTable = []

# Read each line
for line in cowFile:
    # Remove whitespace - PLS page 11
    line = line.strip()
    
    # Split by comma - PLS page 11
    parts = line.split(",")
    name = parts[0]
    breed = parts[1]
    tag = int(parts[2])
    
    # Create key - PLS page 12 for slicing, page 6 for //
    key = breed[0:2] + str(tag // 100) + name[0:2]
    
    # Create record and append - PLS page 10
    record = [key, tag, name, breed]
    cowTable.append(record)

cowFile.close()
showTable()
05

Calculation Examples

πŸ“
Prism Volume Calculator with Formatting
June 2023, Question 4 (15 marks)

Calculate the volume of a triangular prism with input validation and formatted output.

Key PLS References

Round Function

round(x, n) - rounds x to n decimal places

Page 9
Format String

{:8.2f} - 8 columns, 2 decimal places

Page 12

Understanding Format Strings (PLS Page 12)

# Format: {:<alignment><width>.<precision><type>}
#
# {:8.2f} means:
#   8 = total width (8 characters)
#   .2 = 2 decimal places
#   f = fixed-point (decimal) number

layout = "{:8.2f}"
print("Volume:", layout.format(volume), "cubic units")
# Complete solution
base = float(input("Enter base: "))
height = float(input("Enter height: "))
length = float(input("Enter length: "))

# Validate all > 0 - PLS page 6
if base > 0 and height > 0 and length > 0:
    # Calculate area: A = 0.5 Γ— b Γ— h
    area = 0.5 * base * height
    print("Area:", round(area, 2))
    
    # Calculate volume: V = A Γ— l
    volume = area * length
    
    # Formatted output - PLS page 12
    layout = "{:8.2f}"
    print("Volume:", layout.format(volume), "cubic units")
else:
    print("Invalid input")

print("Goodbye")
πŸ•
CafΓ© Ingredients Calculator
June 2024, Question 4 (15 marks)

Calculate ingredient quantities for community events, rounding up to whole packs.

The math.ceil() Function

When you can't order partial bags or packs, use math.ceil() to round UP.

πŸ’‘ PLS Page 13

math.ceil(<r>) returns the smallest integer not less than r. So math.ceil(2.1) returns 3, and math.ceil(2.0) returns 2.

import math

adults = int(input("Enter number of adults: "))
children = int(input("Enter number of children: "))

# Calculate partial bags of crisps
# Adults: 0.75 bags, Children: 0.33 bags
partialBags = (adults * 0.75) + (children * 0.33)
print("Partial bags required:", partialBags)

# Round up to whole bags - PLS page 13
wholeBags = math.ceil(partialBags)
print("Order", wholeBags, "bags of crisps")
06

Subprograms Examples

🍝
Pasta Shapes Menu System
June 2024, Question 5 (15 marks)

A menu-driven program with functions that return values and procedures that modify arrays.

PLS Page 8: Subprogram Syntax

Procedure (no return)
def procname():
    # commands
Function (with return)
def funcname():
    # commands
    return value
import random

pastaShapes = ["Fusilli", "Penne", "Spaghetti", "Farfalle"]

EXIT = 0
GET_SHAPE = 1
ADD_SHAPE = 2

def getChoice():
    # Function returns user's menu choice - PLS page 8
    choice = int(input("Enter option: "))
    return choice

def getShape():
    # Random index - PLS page 13: randint includes both endpoints
    index = random.randint(0, len(pastaShapes) - 1)
    return pastaShapes[index]

def addShape():
    # Append to list - PLS page 10
    newShape = input("Enter new pasta shape: ")
    pastaShapes.append(newShape)

# Main program
choice = -1
while choice != EXIT:
    print("1. Get random shape")
    print("2. Add new shape")
    print("0. Exit")
    
    choice = getChoice()
    
    if choice == GET_SHAPE:
        shape = getShape()
        print("Random shape:", shape)
    elif choice == ADD_SHAPE:
        addShape()
    elif choice != EXIT:
        print("Invalid option")
πŸ†”
User ID Generator with ord()
June 2023, Question 5 (15 marks)

Generate user IDs using string manipulation and ASCII values.

Understanding ord() vs int()

πŸ’‘ Critical Distinction (PLS Page 9)

int("5") returns 5 (the numeric value)
ord("5") returns 53 (the ASCII code)

# For user "Viola Bassir" born 15/06/2005
# ID = "bassirv" + sum of ASCII values of "15062005"

# Calculate number part using ord() - PLS page 9
dob = "15062005"
total = 0
for char in dob:
    total = total + ord(char)
    # ord("1")=49, ord("5")=53, ord("0")=48...

# total = 49+53+48+54+50+48+48+53 = 403
# Final ID: "bassirv403"
07

Quick Reference by Question Type

Question Type Key PLS Sections Pages
Debugging (syntax errors) Data types, Operators, Selection/Iteration syntax 5-7
Debugging (logic errors) Operators (and/or), Range behaviour 6, 7, 9
File handling Files section, String manipulation 8, 11
Calculations Arithmetic operators, Math library, Round 6, 9, 13
Subprograms Subprograms section, Return values 8
String processing String subprograms, Slicing, Format 11-12
Random selection Random library module 13
Searching/Validation While loops, Relational operators 6, 7
Turtle graphics Turtle graphics section 14-16

Common Mistakes to Avoid

❌ Boolean Capitalisation

Python uses True and False with capital letters, not true or false.

❌ Range Endpoint

range(5) gives 0,1,2,3,4 β€” it excludes the endpoint. randint(0,4) includes both endpoints.

❌ and vs or

Use or when checking "outside a range". A value can't be both <5 AND >10.

❌ File Returns Strings

Reading from files always returns strings. Convert numbers with int() or float().