Programming Fundamentals
Key Definition
Programming is the process of writing instructions (code) that a computer can execute to solve a problem or perform a task. Programs are written using programming languages.
Algorithm vs Program - What's the Difference?
Think of it like a recipe:
- Algorithm = The recipe written on paper (the plan in plain English or pseudocode)
- Program = Actually cooking the meal following the recipe (the algorithm converted into code a computer can run)
A well-written algorithm is like a clear recipe - it's easy to follow and should work every time! A program is when you actually make the computer "cook" by running the code.
Paper 2 Information
Topic 6 is assessed in Paper 2: Problem Solving with Programming. This is a 2-hour on-screen exam where you write, test and modify programs using Python.
Variables and Constants
Variables
- Named storage locations in memory
- Value can change during program execution
- Example:
score = 0
Constants
- Named values that don't change
- Value fixed throughout program
- Example:
PI = 3.14159
Assignment and Operators
| Operator Type | Operators | Examples |
|---|---|---|
| Assignment | = | name = "Alice" |
| Arithmetic | + - * / // % ** | total = a + b, remainder = 10 % 3 |
| Comparison | == != < > <= >= | if age >= 18: |
| Logical | AND, OR, NOT | if age >= 18 AND hasID: |
Input and Output
Python Examples
# Output - displaying to user
print("Hello, World!")
print("Your score is:", score)
# Input - getting data from user
name = input("Enter your name: ")
age = int(input("Enter your age: "))
Key Fact
In Python, input() always returns a string. To get a number, you must convert it using int() or float().
Try It Yourself - Variables and Output
Edit the code below and click "Run Code" to see the output:
Challenge 1
Modify the code above to:
- Change the name to your own name
- Add a variable called
subjectwith your favourite subject - Print a message that includes all four variables
Craig 'n' Dave: Programming Fundamentals
Variables, constants and the basics of programming
Craig 'n' Dave: Abstraction and Decomposition
Using abstraction and decomposition to solve problems
Craig 'n' Dave: Algorithmic Thinking
Developing algorithms to solve problems
Craig 'n' Dave: Pseudocode and Flow Diagrams
How to produce algorithms using pseudocode and flowcharts
Craig 'n' Dave: Variables, Constants and Data Types
Using data types, casting, variables and assignments
Craig 'n' Dave: User Input and Display Output
Getting input from users and displaying output
Data Types and Structures
Why Do Data Types Matter?
Think of data types like different types of containers:
- Integer = A box that only holds whole items (like marbles: 1, 2, 3...)
- Float = A measuring jug that can hold precise amounts (like 2.5 litres)
- String = A label maker that stores text (like "Hello")
- Boolean = A light switch - only ON (True) or OFF (False)
Why it matters: If you try to put water (2.5) in a marble box (integer), it becomes 2 - you lose the .5! The computer needs to know what type of data it's storing.
Basic Data Types
| Data Type | Description | Examples |
|---|---|---|
| Integer (int) | Whole numbers (positive or negative) | 42, -7, 0 |
| Float (real) | Decimal numbers | 3.14, -0.5, 2.0 |
| String (str) | Text/characters in quotes | "Hello", 'A' |
| Boolean (bool) | True or False values | True, False |
| Character (char) | Single character | 'A', '7', '!' |
Type Casting (Converting Data Types)
Converting between data types:
# String to Integer
age = int("25")
# String to Float
price = float("19.99")
# Number to String
text = str(42)
# Integer to Float
decimal = float(10) # becomes 10.0
Type Coercion - Automatic Conversion
Sometimes Python automatically converts data types for you. This is called type coercion.
x = 1 # integer
y = 2.5 # float
z = x + y # z becomes 3.5 (float!)
The rule: When you mix an integer with a float, Python automatically converts the result to a float. It's like mixing whole apples with apple slices - you end up with slices!
Common Mistake: input() Always Returns a String!
When you use input(), Python always gives you a string - even if the user types a number!
# WRONG - will crash or give unexpected results!
age = input("Enter age: ") # age is a STRING like "15"
new_age = age + 1 # ERROR! Can't add string + number
# CORRECT - convert to integer first
age = int(input("Enter age: ")) # age is now INTEGER 15
new_age = age + 1 # Works! new_age is 16
Arrays (Lists)
Arrays store multiple values of the same type in a single variable:
# Creating an array/list
scores = [85, 92, 78, 95, 88]
names = ["Alice", "Bob", "Charlie"]
# Accessing elements (index starts at 0)
first = scores[0] # 85
second = names[1] # "Bob"
# Modifying elements
scores[2] = 80
# Array length
length = len(scores) # 5
# Looping through an array
for score in scores:
print(score)
Key Fact
Array indices start at 0, not 1. So in an array of 5 elements, valid indices are 0, 1, 2, 3, 4.
2D Arrays
Arrays within arrays, like a table with rows and columns:
# Creating a 2D array (3 rows, 4 columns)
grid = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
# Accessing elements: grid[row][column]
value = grid[1][2] # 7 (row 1, column 2)
# Looping through 2D array
for row in grid:
for item in row:
print(item)
String Operations
Strings Are Like a Row of Boxes!
Think of a string as a row of numbered boxes, each holding ONE character. The numbering starts at 0, not 1!
| C | o | m | p | u | t | e | r |
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
word = "Computer"
print(word[0]) # Output: C
print(word[3]) # Output: p
print(word[7]) # Output: r
Remember: The last index is always LENGTH - 1. "Computer" has 8 letters, so the last index is 7!
String Traversal - Going Through Each Character
To look at every character in a string one by one, use a FOR loop:
# Traversal - visit each character
word = "Hello"
for letter in word:
print(letter)
# Output: H, e, l, l, o (each on a new line)
# Traversal with index position
word = "Hello"
for i in range(len(word)):
print("Position", i, "=", word[i])
String Slicing - Extracting Parts of a String
Slicing is Like Cutting a Cake!
Use [start:end] to cut out a piece. The slice goes from start up to (but NOT including) end.
word = "Computer"
print(word[0:4]) # "Comp" (positions 0,1,2,3)
print(word[4:8]) # "uter" (positions 4,5,6,7)
print(word[:4]) # "Comp" (from start to 4)
print(word[4:]) # "uter" (from 4 to end)
| Operation | Python Code | Result |
|---|---|---|
| Length | len("Hello") |
5 |
| Concatenation (joining) | "Hello" + " World" |
"Hello World" |
| Substring (slice) | "Hello"[1:4] |
"ell" |
| Upper case | "Hello".upper() |
"HELLO" |
| Lower case | "Hello".lower() |
"hello" |
| Character at index | "Hello"[0] |
"H" |
| Find position | "Hello".find("l") |
2 (first occurrence) |
| Check if contains | "e" in "Hello" |
True |
Craig 'n' Dave: Data Types and Arrays
Integers, strings, booleans and array operations
Craig 'n' Dave: 1D and 2D Arrays
Using one and two dimensional data structures
Craig 'n' Dave: String Manipulation
Basic string operations and formatting output
Past Paper Question
Q: Write code to find the largest number in an array called 'numbers'. (4 marks)
largest = numbers[0]
for num in numbers:
if num > largest:
largest = num
print(largest)
Try It Yourself - Arrays
Practice working with arrays (lists) in Python:
Challenge 2
Modify the code to find the highest and lowest scores in the array. Hint: Start with highest = scores[0]
Control Flow
Key Definition
Control flow determines the order in which statements are executed. The three main constructs are: sequence, selection (if/else), and iteration (loops).
Selection (IF Statements)
Making decisions in code:
Selection is Just Decision-Making!
You use selection in real life all the time:
- IF it's raining THEN take an umbrella
- IF I have money THEN buy lunch ELSE bring packed lunch
- IF score >= 90 THEN "A" ELIF score >= 80 THEN "B" ELSE "C"
# Simple IF
if age >= 18:
print("You can vote")
# IF-ELSE
if score >= 50:
print("Pass")
else:
print("Fail")
# IF-ELIF-ELSE
if grade >= 90:
print("A")
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
else:
print("Below C")
Iteration (Loops)
Two Types of Loops - Know the Difference!
Loops repeat instructions. There are two types:
Definite (FOR loop)
You KNOW how many times to repeat.
"Do 10 star jumps" - you know it's exactly 10!
Indefinite (WHILE loop)
You DON'T know - repeat until something happens.
"Keep guessing until you're right" - could be 1 guess or 100!
FOR Loop (Definite/Count-controlled)
Repeats a fixed number of times:
# Print 1 to 5
for i in range(1, 6):
print(i)
# Loop through array
for name in names:
print(name)
WHILE Loop (Condition-controlled)
Repeats while condition is true:
# Count to 5
count = 1
while count <= 5:
print(count)
count = count + 1
# Until user quits
while answer != "quit":
answer = input()
Nested Structures
Putting control structures inside each other:
# Nested IF
if age >= 18:
if hasLicense:
print("Can drive")
else:
print("Need license")
# Nested loops (multiplication table)
for i in range(1, 4):
for j in range(1, 4):
print(i * j, end=" ")
print() # New line
When to Use Each Loop
- FOR loop: When you know how many times to repeat
- WHILE loop: When you don't know how many times (e.g., until user enters valid input)
Craig 'n' Dave: Selection and Iteration
IF statements, FOR loops and WHILE loops
Craig 'n' Dave: The Three Programming Constructs
Sequence, selection and iteration
Craig 'n' Dave: Operators in Programs
Using arithmetic, comparison and logic operators
Past Paper Question
Q: Write a program that asks for numbers until -1 is entered, then displays the total. (5 marks)
total = 0
number = int(input("Enter number (-1 to stop): "))
while number != -1:
total = total + number
number = int(input("Enter number (-1 to stop): "))
print("Total:", total)
Try It Yourself - Loops and Selection
Practice using IF statements and loops:
Challenge 3
Write a program that prints the multiplication table for the number 7 (7x1 through 7x12). Use a FOR loop!
Random Numbers
Random numbers are used in games, simulations, and anywhere you need unpredictable values.
When Do You Need Random Numbers?
- Rolling dice in a game (random number 1-6)
- Shuffling a deck of cards
- Generating a random password
- Making a "guess the number" game
- Choosing a random winner from a list
# First, import the random module
import random
# Generate a random integer between 1 and 10
number = random.randint(1, 10)
print("Random number:", number)
# Generate a random integer between 1 and 6 (like a dice)
dice = random.randint(1, 6)
print("You rolled:", dice)
# Pick a random item from a list
colours = ["red", "blue", "green", "yellow"]
chosen = random.choice(colours)
print("Random colour:", chosen)
Don't Forget to Import!
You must write import random at the TOP of your program before you can use any random functions. This tells Python to load the random number tools.
Try It Yourself - Random Numbers
Create a simple dice roller:
Challenge: Coin Flip
Create a program that simulates flipping a coin 10 times and counts how many heads and tails you get. Hint: Use random.choice(["Heads", "Tails"])
Subprograms
Key Definition
Subprograms are named blocks of code that can be called from elsewhere in the program. They help organise code, reduce repetition, and make programs easier to maintain.
Functions vs Procedures
Function
- Returns a value
- Can be used in expressions
- Example:
result = calculate(5)
def square(n):
return n * n
answer = square(4) # 16
Procedure
- Does not return a value
- Performs an action
- Example:
displayMessage()
def greet(name):
print("Hello,", name)
greet("Alice") # Hello, Alice
Parameters and Arguments
Parameters vs Arguments - What's the Difference?
Think of a function like a vending machine:
- Parameters = The SLOTS in the machine (labelled "coins" and "selection")
- Arguments = The actual THINGS you put in (your 50p coin and button B3)
Parameters are defined when you CREATE the function. Arguments are the actual values you PASS when you CALL it.
# Parameters are the variables in the function definition
def add(a, b): # a and b are PARAMETERS (the slots)
return a + b
# Arguments are the values passed when calling
result = add(5, 3) # 5 and 3 are ARGUMENTS (actual values)
Parameters
In the function definition
def greet(name):
Arguments
When calling the function
greet("Alice")
Local vs Global Variables
| Variable Type | Scope | Where Declared |
|---|---|---|
| Local | Only accessible inside the subprogram | Inside a function/procedure |
| Global | Accessible anywhere in the program | Outside all functions (main program) |
score = 0 # Global variable
def addPoints(points):
global score # Access global variable
score = score + points
def calculate():
total = 100 # Local variable
return total
Benefits of Using Subprograms
Why Use Subprograms?
Analogy: Think of subprograms like LEGO blocks. Instead of building everything from scratch each time, you create reusable pieces that snap together. One "wheel" block can be used in many different vehicles!
Reusability
Write code once, use it many times. No copying and pasting!
Shorter Programs
Less code = less memory used, faster to write.
Easier Debugging
Test each function separately. Find bugs faster!
Team Work
Different people can work on different functions at the same time.
Easy Maintenance
Need to change something? Update it in ONE place, not everywhere!
Readability
calculateAverage() is easier to understand than 10 lines of maths!
Built-in Functions
Python comes with ready-made functions you can use immediately - no need to write them yourself!
Examples: print(), len(), input(), int(), str(), range()
Craig 'n' Dave: Functions and Procedures
Subprograms, parameters and return values
Craig 'n' Dave: Using Pre-existing Subprograms
How to use pre-existing and user-devised subprograms
Craig 'n' Dave: Local and Global Variables
Variable scope in programming
Craig 'n' Dave: Math and Time Modules
Using built-in Python modules
Craig 'n' Dave: The Turtle Module
Graphics programming with Python Turtle
Try It Yourself - Functions
Practice creating and using functions:
Challenge 4
Create a function called calculate_average(numbers) that takes an array of numbers and returns the average. Test it with [10, 20, 30, 40, 50].
File Handling & Validation
Key Definition
File handling allows programs to read data from and write data to files. This enables data to be stored permanently (persistence) and shared between different programs or users.
Reading from CSV Files
CSV (Comma Separated Value) files store data in rows, with values separated by commas. They're commonly used for storing tabular data like spreadsheets.
Writing to CSV Files
File Modes
- "r" - Read mode (file must exist)
- "w" - Write mode (creates new file or overwrites existing)
- "a" - Append mode (adds to end of file)
Input Validation
Validation checks that data entered by the user is sensible and usable before processing. The specification requires you to understand four types of validation:
| Validation Type | Description | Example |
|---|---|---|
| Length Check | Checks data is within acceptable length limits | Password must be 8-20 characters |
| Presence Check | Checks that required data has been entered (not empty) | Username field cannot be blank |
| Range Check | Checks numeric data is within an acceptable range | Age must be between 1 and 120 |
| Pattern Check | Checks data matches a required format/pattern | Email must contain @ symbol |
Validation Code Examples
Authentication
Authentication verifies that users are who they claim to be, typically using a username/ID and password combination:
Important Distinction
Validation checks if data is in the correct format and reasonable.
Authentication checks if the user is who they claim to be.
Both are essential for creating secure and reliable programs.
Craig 'n' Dave: File Handling in Python
Reading and writing to text and CSV files
Craig 'n' Dave: Validation and Authentication
Input validation techniques and user authentication
Past Paper Question
Q: Write a program that reads student names and scores from a CSV file and displays them. (6 marks)
Mark Scheme:
- Open file correctly (1)
- Loop through lines (1)
- Split each line by comma (1)
- Extract name and score (1)
- Display output correctly (1)
- Close file (1)
Challenge 5
Create a login system that:
- Asks for username and password
- Uses presence check to ensure both fields are filled
- Uses length check to ensure password is at least 8 characters
- Authenticates against a dictionary of valid users
- Gives the user 3 attempts before locking them out
Testing and Debugging
Types of Errors
Three Types of Bugs (Errors)
Think of writing code like writing a recipe. There are three ways it can go wrong:
- Syntax error: Like spelling "teaspoon" wrong - the recipe can't be read!
- Logic error: Like saying "add 10 cups of salt" instead of 1 - it runs but tastes terrible!
- Runtime error: Like saying "divide the mixture into zero portions" - impossible to do!
| Error Type | When Detected | Description | Example |
|---|---|---|---|
| Syntax Error | Before running | Code breaks grammar rules; program won't even start | print("Hello - missing quote |
| Logic Error | After running | Code runs successfully but produces WRONG results | average = a + b / 2 (BIDMAS error!) |
| Runtime Error | While running | Program crashes during execution | Division by zero, file not found |
Syntax Errors - "The Computer Can't Read This!"
Syntax errors break Python's grammar rules. The program won't even start - Python tells you immediately!
Missing bracket:
print("Hello"
Missing colon:
if age > 18
Missing quote:
name = "Bob
Typo in keyword:
pritn("Hello")
Logic Errors - "It Runs But It's Wrong!"
The sneakiest errors! Your code runs perfectly but gives the wrong answer. Python can't detect these - you have to find them yourself.
Classic BIDMAS Error
Remember BIDMAS (Brackets, Indices, Division, Multiplication, Addition, Subtraction)?
WRONG:
average = a + b / 2
If a=10, b=20: 10 + 20/2 = 10 + 10 = 20
CORRECT:
average = (a + b) / 2
If a=10, b=20: (10 + 20)/2 = 30/2 = 15
Infinite Loop - The Loop That Never Ends!
Like a hamster wheel that won't stop - the condition never becomes False!
INFINITE LOOP:
x = 1
while x < 10:
print(x)
# Forgot x = x + 1!
FIXED:
x = 1
while x < 10:
print(x)
x = x + 1
Runtime Errors - "It Crashed!"
The program starts fine, but something impossible happens while running and it crashes.
Division by zero:
result = 10 / 0
File not found:
open("missing.txt")
Index out of range:
names[100]
Real World Disaster: Ariane 5 Rocket (1996)
On June 4, 1996, the Ariane 5 rocket exploded just 37 seconds after launch, destroying $370 million worth of satellites!
The cause? A software bug tried to store a number too big for its variable (like trying to fit an elephant in a shoebox). This caused a runtime error that crashed the guidance system.
Lesson: Even one small bug can have HUGE consequences. That's why testing is so important!
Test Data
Why Test with Different Data?
Testing is like checking a door lock works properly. You don't just try ONE key - you test with:
- The correct key (normal data) - it should open
- Keys that are almost right (boundary data) - testing the limits
- Completely wrong keys (erroneous data) - they should NOT open!
Normal Data
Typical values that SHOULD be accepted.
For age 18-65: Test with 25, 40, 55
Boundary Data
Values at the EDGES of what's allowed.
For age 18-65: Test with 17, 18, 65, 66
Erroneous Data
Invalid data that should be REJECTED.
For age 18-65: Test with -5, "abc", 150
Exam Tip - Boundary Testing
For a range like >= 18 AND <= 65, always test BOTH sides of each boundary:
- 17 (should fail - just below lower limit)
- 18 (should pass - AT the lower limit)
- 65 (should pass - AT the upper limit)
- 66 (should fail - just above upper limit)
Trace Tables
What is a Trace Table?
A trace table is like being a detective following footprints. You track what happens to each variable at every step of the program.
Think of it as "playing computer" - you BE the computer and write down what happens in each line!
Why Use Trace Tables?
- Find logic errors: See exactly where your code goes wrong
- Understand loops: Track how many times a loop runs
- Debug code: Figure out why you're getting wrong answers
- Exam requirement: You WILL be asked to complete trace tables!
How to Create a Trace Table
- Create columns for each variable and any condition being tested
- Add a row each time a value changes
- Work through line by line - execute each line in order
- Update values - only write the NEW value when it changes
Example: Tracing a While Loop
# Code to trace:
x = 1
while x < 4:
y = x * 2
x = x + 1
| Line | x | x < 4 | y | Output |
|---|---|---|---|---|
| x = 1 | 1 | - | - | - |
| while x < 4 | 1 | True âś“ | - | - |
| y = x * 2 | 1 | - | 2 | - |
| x = x + 1 | 2 | - | 2 | - |
| while x < 4 | 2 | True âś“ | 2 | - |
| y = x * 2 | 2 | - | 4 | - |
| x = x + 1 | 3 | - | 4 | - |
| while x < 4 | 3 | True âś“ | 4 | - |
| y = x * 2 | 3 | - | 6 | - |
| x = x + 1 | 4 | - | 6 | - |
| while x < 4 | 4 | False âś— | 6 | Loop ends |
Exam Tip - Trace Table Shortcuts
In exams, you don't need to show EVERY line. Just show key moments:
- Initial values (start of program)
- End of each loop iteration
- Final values (when loop ends)
Simplified version (exam-style):
| Iteration | x | x < 4 | y |
|---|---|---|---|
| Start | 1 | True | - |
| 1 | 2 | True | 2 |
| 2 | 3 | True | 4 |
| 3 | 4 | False | 6 |
Using an IDE to Find Errors
What is an IDE?
An IDE (Integrated Development Environment) is like a Swiss Army knife for programmers - it has tools to write, run, test, and debug code all in one place!
Examples: IDLE (comes with Python), Visual Studio Code, PyCharm, Thonny
IDE Features That Help Find Errors
Syntax Highlighting
The IDE colours different parts of your code:
print("Adult")
Keywords (purple), variables (blue), numbers (green), strings (orange)
Error Messages
The IDE tells you EXACTLY what went wrong:
Line 5: name = "Bob
Shows the error type, description, and LINE NUMBER!
Auto-complete
Start typing and the IDE suggests completions:
- Type
pri→ suggestsprint() - Prevents spelling mistakes
- Shows function parameters
Debugger
Step through your code line by line:
- Breakpoints: Pause at specific lines
- Step through: Run one line at a time
- Watch variables: See values change live
Like a trace table, but the IDE does it for you!
Common Python Error Messages (and what they mean!)
| Error Message | What It Means | How to Fix It |
|---|---|---|
SyntaxError: invalid syntax |
You broke Python's grammar rules | Check for missing colons, brackets, quotes |
NameError: name 'x' is not defined |
You're using a variable that doesn't exist | Check spelling! Did you create the variable first? |
TypeError: cannot concatenate str and int |
You're mixing text and numbers wrongly | Use str(number) to convert numbers to text |
IndentationError |
Your code isn't lined up properly | Check your tabs/spaces - be consistent! |
ZeroDivisionError |
You tried to divide by zero | Check the divisor isn't zero before dividing |
IndexError: list index out of range |
You tried to access an item that doesn't exist | Remember arrays start at 0! Check the list length |
Top Tip: READ the Error Message!
Python tries to help you! The error message tells you:
- What type of error it is (SyntaxError, TypeError, etc.)
- Which line the error is on
- What went wrong (description)
Don't panic when you see red text - it's Python trying to help you debug!
Input Validation
Checking that user input is valid before using it.
GIGO - Garbage In, Garbage Out!
If you put bad data INTO a program, you get bad results OUT. It's like making a cake:
- Put in rotten eggs (garbage in) = get a horrible cake (garbage out)
- Put in fresh ingredients (good data) = get a delicious cake (good results)
That's why we validate! We check the input BEFORE the program uses it.
Four Types of Validation Checks
1. Range Check
Checks data is within acceptable minimum and maximum values.
Analogy: Like a theme park ride - you must be between 1.2m and 2.0m tall!
# Range: age must be 0-120
while age < 0 or age > 120:
age = int(input("Invalid!"))
2. Presence Check
Checks that data has actually been entered (not left empty).
Analogy: Like a form that says "Required field" - you can't leave your name blank!
# Check name isn't empty
while name == "":
name = input("Enter name!")
3. Look-up Check
Checks that data matches one of the allowed values in a list.
Analogy: Like a dropdown menu - you can only pick from the options given!
# Must be Yes or No
while choice not in ["Y","N"]:
choice = input("Y or N?")
4. Length Check
Checks that the length of input falls within a specified range.
Analogy: Like a UK postcode - must be 6-8 characters long!
# Postcode: 6-8 chars
while len(postcode) < 6 or len(postcode) > 8:
postcode = input("Invalid!")
Complete Validation Examples
# RANGE CHECK - age must be between 0 and 120
age = int(input("Enter age: "))
while age < 0 or age > 120:
print("Invalid! Age must be between 0 and 120")
age = int(input("Enter age: "))
# PRESENCE CHECK - name cannot be empty
name = input("Enter your name: ")
while name == "":
print("Name is required!")
name = input("Enter your name: ")
# LOOK-UP CHECK - must be one of the valid options
valid_sizes = ["S", "M", "L", "XL"]
size = input("Enter size (S/M/L/XL): ").upper()
while size not in valid_sizes:
print("Invalid size! Choose S, M, L, or XL")
size = input("Enter size: ").upper()
# LENGTH CHECK - UK postcode must be 6-8 characters
postcode = input("Enter UK postcode: ")
while len(postcode) < 6 or len(postcode) > 8:
print("Invalid! Postcode must be 6-8 characters")
postcode = input("Enter UK postcode: ")
Exam Tip - Validation vs Verification
Validation = Checking data is sensible (is age between 0-120?)
Verification = Checking data is correct (is this really YOUR email? Type it twice to confirm!)
File Handling
Why Do We Need Files?
Think about it: when your program ends, all your variables disappear! Files let you save data permanently.
Analogy: Variables are like writing on a whiteboard (erased when you leave). Files are like writing in a notebook (kept forever)!
| Mode | What it Does | Warning! |
|---|---|---|
"r" |
Read - Opens file to read data from it | File must exist or you get an error |
"w" |
Write - Opens file to write data to it | DANGER: Overwrites existing file! |
"a" |
Append - Adds data to end of file | Keeps existing data safe |
Common Mistake: Using "w" Mode!
If you open an EXISTING file with "w" mode, all the old data is deleted! Use "a" (append) if you want to add data without losing what's already there.
File Handling Examples
# Writing to a file (creates new or OVERWRITES existing!)
file = open("data.txt", "w")
file.write("Hello World\n")
file.close()
# Reading entire file
file = open("data.txt", "r")
content = file.read()
file.close()
print(content)
# Reading line by line
file = open("data.txt", "r")
for line in file:
print(line)
file.close()
# APPENDING - adds to end without deleting
file = open("data.txt", "a")
file.write("New line added!\n")
file.close()
# Saving an array to a file (with commas)
scores = [85, 92, 78, 95]
file = open("scores.txt", "w")
for score in scores:
file.write(str(score) + ",")
file.close()
# Reading back into an array
file = open("scores.txt", "r")
data = file.read().split(",") # Split by comma
file.close()
Remember: Always Close Your Files!
Data isn't actually saved until you call file.close(). Forgetting to close can cause data loss or errors!
Test Plans
What is a Test Plan?
A test plan is like a checklist before launch. Before NASA sends a rocket into space, they don't just hope it works - they test EVERYTHING and write down the results!
A test plan documents: what you're testing, what data you'll use, what SHOULD happen, and what ACTUALLY happened.
Test Plan Structure
A good test plan has these columns:
| Test # | Description | Test Data | Data Type | Expected Result | Actual Result | Pass/Fail |
|---|---|---|---|---|---|---|
| 1 | Check valid age accepted | 25 | Normal | "Access granted" | "Access granted" | PASS |
| 2 | Check lower boundary | 18 | Boundary | "Access granted" | "Access granted" | PASS |
| 3 | Check below boundary rejected | 17 | Boundary | "Access denied" | "Access denied" | PASS |
| 4 | Check text rejected | "abc" | Erroneous | Error message | Program crashed! | FAIL |
| 5 | Check negative rejected | -5 | Erroneous | "Access denied" | "Access denied" | PASS |
Expected Result
What SHOULD happen if the program works correctly. You write this BEFORE testing!
Actual Result
What ACTUALLY happened when you ran the test. You write this AFTER testing!
Pass or Fail?
If Expected = Actual, it's a PASS. If they're different, it's a FAIL (bug found!).
Exam Tip - Test Plan Must-Haves
In the exam, make sure your test plan includes:
- At least one normal test (typical valid data)
- At least one boundary test (values at the limits)
- At least one erroneous test (invalid data that should be rejected)
- Expected results written BEFORE you run the test
Craig 'n' Dave: Testing and Debugging
Test data, error types and debugging techniques
Craig 'n' Dave: Importance of Robust Programming
Why programs need to handle errors and unexpected inputs
Craig 'n' Dave: Identifying Syntax, Logic and Runtime Errors
How to find and fix different types of errors
Craig 'n' Dave: Program Maintenance Techniques
Keeping programs working and up to date
Craig 'n' Dave: Evaluating Programs
Evaluating a program for purpose and efficiency
Craig 'n' Dave: Data Validation and Authentication
Validating input and simple authentication routines
Craig 'n' Dave: File Handling Operations
Reading from and writing to files
Past Paper Question
Q: Complete a trace table for this code:
a = 5
b = 3
while a > b:
a = a - 1
b = b + 1
| a | b | a > b |
|---|---|---|
| 5 | 3 | True |
| 4 | 4 | False |
Evaluating Programs
What is Program Evaluation?
Evaluation is like being a judge on a talent show. You look at the program and ask: "Is it any good? Does it do what it's supposed to? Could it be better?"
A program can work correctly but still be poor quality (slow, hard to read, or difficult to use).
The 5 Criteria for Evaluating Programs
Fitness for Purpose
Does it do what it was meant to do?
Check: Does it meet ALL the original requirements? Does it produce the correct outputs?
Usability
Is it easy to use?
Check: Are instructions clear? Is the interface intuitive? Can a beginner figure it out?
Validation (Robustness)
Does it handle bad input without crashing?
Check: What happens if you type letters instead of numbers? Does it give helpful error messages?
Efficiency
Does it run quickly without wasting resources?
Check: Is the code concise? Are there unnecessary loops? Does it use memory wisely?
Readability (Maintainability)
Can other programmers understand the code?
Check: Are variable names meaningful? Are there comments? Is it properly indented?
Memory Trick: "FIVER"
Fitness for purpose
Interface usability
Validation (robustness)
Efficiency
Readability
Remember: A good program should score a FIVER on all five criteria!
Example: Evaluating a Calculator Program
| Criteria | Question to Ask | Example Response |
|---|---|---|
| Fitness | Does it add, subtract, multiply, divide? | Yes, all 4 operations work correctly |
| Usability | Are prompts clear? | Prompts are clear: "Enter first number:" |
| Validation | What if user types "abc"? | Program crashes - needs input validation! |
| Efficiency | Does it run fast? | Yes, calculations are instant |
| Readability | Can another programmer follow it? | Variables are well named, has comments |
Exam Tip - Evaluation Questions
In evaluation questions, don't just say "yes" or "no". Give specific examples:
- Bad: "The program is easy to use" (too vague)
- Good: "The program is easy to use because it displays clear prompts like 'Enter your age:' and gives helpful error messages when invalid data is entered"
Making Code Easy to Read
Key Concept
Code readability means writing code that is easy for humans to understand. This is important because programmers spend more time reading code than writing it!
Why Does Readability Matter?
- You will forget! Come back to your code in a month - will you remember what it does?
- Teamwork: Other programmers need to understand your code
- Debugging: Finding errors is much easier in readable code
- Maintenance: Code often needs updating - readable code is easier to change
Three Ways to Make Code Readable
1. Use Descriptive Names
Variable names should explain what they store.
Bad:
x = 15n1 = "Bob"
Good:
age = 15playerName = "Bob"
2. Use Blank Lines
Separate different sections of code with blank lines - like paragraphs in an essay.
# Get user input
name = input("Name: ")
age = int(input("Age: "))
# Calculate result
result = age * 2
# Display output
print(result)
3. Add Comments
Comments explain WHAT the code does and WHY.
# Check if user is old enough to voteif age >= 18:print("You can vote!")
Example: Bad Code vs Good Code
Hard to Read
n1=int(input())
n2=int(input())
if n1==1:
print("*")
elif n2==2:
print("**")
else:
print("***")
What does this even do?!
Easy to Read
# Get user's choiceuserChoice = int(input("Enter 1, 2 or 3: "))# Display stars based on choiceif userChoice == 1:
print("*")
elif userChoice == 2:
print("**")
else:
print("***")
Clear variable names + comments = understandable!
Exam Tip
In Paper 2, you get marks for code that is readable and well-commented. Even if your solution works, poor readability can lose you marks. Always:
- Use meaningful variable names (not x, y, z)
- Add comments explaining your logic
- Use proper indentation
Topic 6 Quiz
Test Your Knowledge
Complete this 15-question quiz to test your understanding of programming concepts.