💻 Code Reference
Code Examples
Every Python concept from Year 7 basics to Year 9 exam-level, plus the complete HTML reference for your web-authoring unit. Each snippet is annotated line by line.
01
Printing to the screen
The very first command every programmer learns.
print()
displays text or values in the console output.
print("Hello, World!") # Prints the text between the quotes print("My name is Alice") # You can print anything you like print(42) # Numbers don't need quotes print(3.14) # Decimals work too print("Sum:", 5 + 3) # Comma separates items — prints: Sum: 8 print() # Empty print() = blank line
| Line | What it does |
|---|---|
print("Hello, World!") |
Displays the string "Hello, World!" on screen. The text must be in quotes. |
print(42) |
Numbers are printed without quotes — Python knows it's a number not text. |
print("Sum:", 5+3) |
A comma joins a string and a calculated value. Output:
Sum: 8
|
✏️ Try It Yourself
Q1. Write a line of code that prints your name and age on separate
lines using two print() statements.
Q2. What will
print(10 * 5)
output? Try it mentally first.
Each print() outputs one line. Put your name in quotes — it's a
string. Your age is a number, no quotes needed.
print("Alice")
print(13)
# Q2 output: 50
02
Getting input from the user
input()
pauses the program and waits for the user to type something. It
always returns a string — even if they type a
number.
name = input("What is your name? ") # Stores whatever the user types print("Hello,", name) # Uses the stored value # ⚠️ input() always returns a STRING. To do maths, convert it first: age_text = input("Enter your age: ") # "14" — still a string! age = int(age_text) # Now it's the integer 14 print("Next year you will be", age + 1) # Works! Output: Next year you will be 15 # Shortcut — convert immediately on one line: score = int(input("Enter score: ")) # Gets input AND converts in one step height = float(input("Enter height (m): "))# Use float() for decimals
Common mistake: If a user enters "14" and you try
to do
age + 1 without converting, Python will give a
TypeError because you can't add a string and a
number. Always use int() or float() after
input() when you need maths.
✏️ Try It Yourself
Q1. Write a program that asks for two numbers and prints their sum.
Q2. Why would
print(input("Age: ") + 1)
cause an error?
Remember — input() always returns a string. You need int() before
you can add numbers.
num1 = int(input("First number: "))
num2 = int(input("Second number: "))
print("Sum:", num1 + num2)
# Q2: input() returns a string. "14" + 1 is TypeError — you can't add string + integer.
03
Declaring and using variables
A variable is a named box in memory. You assign a value with
=. Python automatically works out the data type — this is called
dynamic typing.
# The four main data types: name = "Alice" # str — text in quotes (single or double) age = 13 # int — whole number, no decimal height = 1.65 # float — decimal (floating point) number is_student = True # bool — only True or False (capital T/F!) # Checking the type print(type(name)) # <class 'str'> print(type(age)) # <class 'int'> # Variables can change value age = 14 # Reassign — age is now 14 age = age + 1 # Use old value to make new value — now 15 age += 1 # Shorthand for age = age + 1 — now 16 # Type conversion score_str = "87" # This is a string score_int = int(score_str)# Convert to integer: 87 score_flt = float(score_str)# Convert to float: 87.0 back_str = str(87) # Integer to string: "87"
| Type | Example value | Use for |
|---|---|---|
str |
"Alice", "123" |
Names, messages, any text |
int |
42, -7, 0 |
Counting, scores, ages |
float |
3.14, 9.81 |
Prices, measurements, percentages |
bool |
True, False |
On/Off switches, conditions |
✏️ Try It Yourself
Q1. Create variables for your name, age, and whether you like coding
(True/False). Print all three.
Q2. What is the data type of
x = "42"? And
y = 42? What is different?
Use = to assign. Strings need quotes, integers don't, and True/False
are Python booleans — capital T/F, no quotes needed.
name = "Bob" age = 14 likes_coding = True print(name, age, likes_coding) # Q2: x = "42" is str (has quotes). y = 42 is int. Quotes make it a string!
04
Arithmetic & comparison operators
Python follows BIDMAS (Brackets, Indices, Division,
Multiplication, Addition, Subtraction). There are also special
operators like
%
(modulus) and
//
(integer division).
# ARITHMETIC OPERATORS print(10 + 3) # 13 — addition print(10 - 3) # 7 — subtraction print(10 * 3) # 30 — multiplication print(10 / 3) # 3.333... — division (always gives float) print(10 // 3) # 3 — integer division (whole number only) print(10 % 3) # 1 — modulus (the remainder after dividing) print(2 ** 8) # 256 — exponent (2 to the power of 8) # BIDMAS — order matters! print(2 + 3 * 4) # 14 — multiplication FIRST, then add print((2 + 3) * 4) # 20 — brackets override BIDMAS # COMPARISON OPERATORS (return True or False) print(5 == 5) # True — equal to (note: == not =) print(5 != 3) # True — not equal to print(10 > 7) # True — greater than print(3 >= 3) # True — greater than or equal to print(4 < 2) # False — less than # LOGICAL OPERATORS print(True and False) # False — BOTH must be True print(True or False) # True — at least ONE must be True print(not True) # False — reverses the boolean # Useful built-in maths functions print(abs(-15)) # 15 — absolute value (removes minus sign) print(round(3.756, 2))# 3.76 — round to 2 decimal places print(max(4, 9, 2)) # 9 — largest of the given values print(min(4, 9, 2)) # 2 — smallest value
✏️ Try It Yourself
Q1. What is the output of
print(17 % 5)? What does it represent?
Q2. A cinema has 250 seats. 3 school classes of 29 students are
attending. Write code to calculate remaining seats.
Remaining = total seats − (number of classes × students per class)
# Q1: 17 % 5 = 2 (the remainder when 17 is divided by 5: 5×3=15, 17-15=2)
seats = 250
students = 3 * 29
remaining = seats - students
print("Remaining seats:", remaining) # 163
05
String operations — concatenation, slicing and methods
Strings are sequences of characters. You can join them
(concatenation), extract parts
(slicing), and transform them using
methods like
.upper()
and
.replace().
word = "Computing" # Length print(len(word)) # 9 — number of characters # Indexing — position starts at 0 print(word[0]) # C — first character print(word[4]) # u — 5th character (index 4) print(word[-1]) # g — last character print(word[-3]) # i — 3rd from end # Slicing — word[start:stop] (stop is NOT included) print(word[0:4]) # Comp — characters 0,1,2,3 print(word[4:]) # uting — from index 4 to end print(word[:7]) # Computi — from start up to index 7 # String methods (they don't change the original — they return new strings) print(word.upper()) # COMPUTING print(word.lower()) # computing print(word.replace("ing", "er")) # Computer print(word.count("i")) # 1 — how many times "i" appears print("comp" in word) # False — case-sensitive! print("Comp" in word) # True # Concatenation (joining strings) first = "Hello" last = "World" print(first + " " + last) # Hello World # f-strings — the modern, clean way to embed variables in text name = "Bob" score = 87 print(f"Student {name} scored {score}%") # Student Bob scored 87% print(f"Grade: {score/100:.1%}") # Grade: 87.0% print(f"Pi is approximately {3.14159:.2f}") # Pi is approximately 3.14
✏️ Try It Yourself
Q1. Given
s = "algorithm", write code to print just "algo" using slicing.
Q2. Use an f-string to print: "I am 14 years old and my score was
92/100"
Slicing uses s[start:end], indexes start at 0. "algo" is the first 4
characters: s[0:4]. For f-strings, wrap variables in curly braces:
f"I am {age} years old".
s = "algorithm"
print(s[0:4]) # algo
age = 14
score = 92
print(f"I am {age} years old and my score was {score}/100")
06
Conditional branching
Selection lets your program make decisions. The
if
statement tests a condition.
elif
adds extra conditions.
else
catches everything that didn't match.
Indentation (4 spaces) is mandatory in Python!
# Basic if / else temperature = 22 if temperature >= 25: # Condition to test print("It's hot — wear sunscreen!") # Runs if condition is True else: # Runs if condition is False print("Not too hot today.") # Multiple conditions with elif (else-if) score = int(input("Enter score: ")) if score >= 90: grade = "A*" # 90 or above elif score >= 80: grade = "A" # 80–89 elif score >= 70: grade = "B" # 70–79 elif score >= 60: grade = "C" # 60–69 elif score >= 50: grade = "D" # 50–59 else: grade = "U" # Below 50 print(f"Grade: {grade}") # AND / OR in conditions age = 15 has_ticket = True if age >= 12 and has_ticket: # BOTH must be True print("Welcome to the show!") else: print("Sorry, you cannot enter.") # Nested if (an if inside an if) weather = "sunny" if weather == "sunny": if temperature > 20: print("Perfect beach day!") else: print("Sunny but chilly.") else: print("Stay inside.")
Python uses indentation (spaces) to group code.
The standard is 4 spaces. If you mix tabs and
spaces, you'll get an IndentationError.
✏️ Try It Yourself — BMI Classifier
Write a program that asks for a BMI value and prints: "Underweight"
(<18.5), "Healthy" (18.5–24.9), "Overweight" (25–29.9), or
"Obese" (≥30).
Use float(input(...)) to get a decimal. Chain conditions: if bmi
< 18.5 → Underweight, elif bmi < 25 → Healthy, elif bmi <
30 → Overweight, else → Obese.
bmi = float(input("Enter your BMI: "))
if bmi < 18.5:
print("Underweight")
elif bmi < 25:
print("Healthy")
elif bmi < 30:
print("Overweight")
else:
print("Obese")
07
for loops — definite iteration
A
for
loop repeats a fixed number of times. Use
range()
to generate a sequence of numbers, or loop directly over a
list/string.
# range(stop) — 0 up to (but not including) stop for i in range(5): print("Count:", i) # 0, 1, 2, 3, 4 # range(start, stop) — start up to (not including) stop for i in range(1, 11): # 1 to 10 print(i, "x 3 =", i * 3) # range(start, stop, step) for i in range(0, 21, 2): # Even numbers: 0, 2, 4, ... 20 print(i, end=" ") # end=" " keeps on same line # Looping over a list subjects = ["Maths", "English", "Computing", "Science"] for subject in subjects: print(f"I study {subject}") # Looping over a string (character by character) for letter in "Python": print(letter, end="-") # P-y-t-h-o-n- # Accumulator pattern — total in a loop total = 0 # Start at 0 BEFORE the loop for n in range(1, 101): # 1 to 100 total += n # Add each number to total print("Sum 1–100:", total) # 5050
✏️ Try It Yourself
Q1. Print the 7 times table from 1×7 to 12×7 using a for loop.
Q2. Use a loop to count how many letters in "supercalifragilistic"
are vowels (a, e, i, o, u).
Use range(1, 13) to get numbers 1–12. For vowels, loop through each
letter and check if letter in "aeiou". Use a counter starting at 0.
# Q1 - 7 times table
for i in range(1, 13):
print(f"{i} x 7 = {i * 7}")
# Q2 - Count vowels
word = "supercalifragilistic"
count = 0
for letter in word:
if letter in "aeiou":
count += 1
print("Vowels:", count) # 9
08
while loops — indefinite iteration & validation
A
while
loop keeps repeating as long as a condition is True.
Perfect for user input validation where you don't know how many
attempts it will take.
# Basic while loop count = 1 # Initialise before the loop while count <= 5: # Condition checked EACH iteration print("Count:", count) count += 1 # MUST update — or infinite loop! # Input validation — keep asking until valid age = int(input("Enter age (5–120): ")) while age < 5 or age > 120: # Reject invalid values print("Invalid — must be 5 to 120") age = int(input("Try again: ")) print("Valid age:", age) # While True loop with break — runs forever until break while True: answer = input("Type 'quit' to exit: ") if answer.lower() == "quit": print("Goodbye!") break # Exits the loop immediately print(f"You typed: {answer}")
Infinite loop danger: If the while condition never
becomes False and there's no
break, your program will
run forever and freeze. Always make sure something inside the loop
can make the condition False.
09
Creating, accessing and modifying lists
A list stores multiple values in one variable. In Python, lists
use square brackets and are ordered, mutable (changeable), and can
hold mixed types. Index always starts at 0.
# Creating lists scores = [85, 92, 78, 65, 99] # List of integers names = ["Alice", "Bob", "Cara"] # List of strings empty = [] # Empty list (start adding later) # Accessing elements — index starts at 0 print(scores[0]) # 85 — first element print(scores[2]) # 78 — third element print(scores[-1]) # 99 — last element print(scores[1:4]) # [92, 78, 65] — slice # Modifying lists scores[0] = 90 # Change first element to 90 scores.append(75) # Add 75 to the END scores.insert(2, 50) # Insert 50 at position 2 (pushes others right) scores.remove(65) # Remove first occurrence of 65 removed = scores.pop()# Remove AND return the last element # Useful list operations print(len(scores)) # Number of elements in the list print(sum(scores)) # Total of all numbers print(max(scores)) # Highest value print(min(scores)) # Lowest value print(scores.index(78)) # Find position of value 78 print(78 in scores) # True if 78 is in the list # Sorting scores.sort() # Sort ascending (modifies original) scores.sort(reverse=True) # Sort descending sorted_copy = sorted(scores) # Returns new sorted list, keeps original # 2D list (list of lists — like a table) grid = [[1,2,3], [4,5,6], [7,8,9]] print(grid[1][2]) # 6 — row 1 (middle), column 2 (rightmost)
✏️ Try It Yourself
Q1. Create a list of 5 temperatures. Write code to find the average,
highest and lowest temperature.
Q2. Write a loop that goes through a list of names and prints only
names longer than 4 characters.
Python has built-ins: sum(), max(), min(), len(). Average =
sum(list) / len(list). For filtering names, use if len(name) > 5
inside your loop.
# Q1
temps = [22.5, 18.0, 25.3, 14.8, 20.1]
print("Average:", sum(temps)/len(temps))
print("Highest:", max(temps))
print("Lowest:", min(temps))
# Q2
names = ["Ali", "Sophia", "Ben", "Charlotte", "Jo"]
for name in names:
if len(name) > 4:
print(name)
10
Defining and calling functions with parameters & return values
Functions let you write code once and use it many times. A
parameter is a variable in the function
definition. An argument is the actual value
passed in.
return
sends a value back to the caller.
# Procedure — does a task, no return value def greet(name): # 'name' is the parameter print(f"Hello, {name}!") # Uses the parameter greet("Alice") # "Alice" is the argument — prints: Hello, Alice! greet("Bob") # Re-use with different argument # Function — returns a value def calculate_area(length, width): # Two parameters area = length * width # Local variable — only exists here return area # Sends result back to caller room = calculate_area(5, 3) # Call with arguments 5 and 3 field = calculate_area(100, 50) # Reuse function easily print(f"Room: {room} m²") # 15 # Default parameter values def power(base, exponent=2): # exponent defaults to 2 if not given return base ** exponent print(power(5)) # 25 — uses default exponent=2 print(power(2, 10)) # 1024 — overrides default # Global vs Local scope total = 0 # GLOBAL — accessible everywhere def add_to_total(amount): global total # Declare we want to use/modify the global temp = amount * 2 # LOCAL — only exists inside this function total += amount add_to_total(10) add_to_total(5) print(total) # 15 # Returning multiple values def min_max(data): return min(data), max(data) # Returns a tuple of two values lo, hi = min_max([4, 9, 2, 7]) # Unpack into two variables print(f"Min={lo}, Max={hi}") # Min=2, Max=9
✏️ Try It Yourself — Build a Calculator
Write four functions:
add(a,b),
subtract(a,b),
multiply(a,b),
divide(a,b). Each should return the result. For divide, return an error
message if b is 0.
Each function takes two parameters and uses return to give back the
result. For divide, check if b == 0 first to avoid a
ZeroDivisionError — return an error string in that case.
def add(a, b): return a + b
def subtract(a, b): return a - b
def multiply(a, b): return a * b
def divide(a, b):
if b == 0:
return "Error: Cannot divide by zero"
return a / b
print(add(5, 3)) # 8
print(divide(10, 0)) # Error: Cannot divide by zero
11
Linear Search — the simple search algorithm
Linear search checks each item
one by one from the start until it finds the
target or reaches the end. Works on any list — sorted or unsorted.
Best case: O(1). Worst case: O(n).
def linear_search(data, target): """Search through data list for target value. Returns index if found, -1 if not found.""" for i in range(len(data)): # i goes from 0 to last index if data[i] == target: # Check each element return i # Found! Return its index return -1 # Not found — return -1 by convention # Testing the function numbers = [34, 7, 23, 32, 5, 62] result = linear_search(numbers, 32) if result != -1: print(f"Found 32 at index {result}") # Found 32 at index 3 else: print("32 not found in the list") # Works for strings too names = ["Alice", "Bob", "Charlie", "Diana"] print(linear_search(names, "Charlie")) # 2 print(linear_search(names, "Eve")) # -1 (not found)
| Scenario | Comparisons needed |
|---|---|
| Best case (target is first) | 1 |
| Average case | n ÷ 2 |
| Worst case (target is last or missing) | n (all elements) |
12
Bubble Sort — compare and swap neighbours
Bubble sort makes multiple passes through the
list. On each pass, it compares adjacent pairs and swaps them if
they're in the wrong order. After each pass, the largest unsorted
element "bubbles up" to its correct position.
def bubble_sort(data): """Sort a list in ascending order using bubble sort.""" n = len(data) # Total number of items for pass_num in range(n - 1): # n-1 passes maximum swapped = False # Track if any swap happened this pass for i in range(0, n - pass_num - 1): # Don't check already-sorted end if data[i] > data[i + 1]: # Left item bigger than right? # Swap them — Python's elegant swap: data[i], data[i+1] = data[i+1], data[i] swapped = True # Record that a swap happened if not swapped: # If NO swaps, list is already sorted break # Optimisation — stop early! return data # Demonstration with trace nums = [64, 25, 12, 22, 11] print("Before:", nums) # [64, 25, 12, 22, 11] bubble_sort(nums) print("After: ", nums) # [11, 12, 22, 25, 64] # TRACE TABLE (mental model): # Pass 1: [25,12,22,11,64] — 64 bubbles to end # Pass 2: [12,22,11,25,64] — 25 moves right # Pass 3: [12,11,22,25,64] — 22 in place # Pass 4: [11,12,22,25,64] — done!
✏️ Exam-Style Question
The list [3, 1, 4, 1, 5] is to be sorted using bubble sort. Show the
state of the list after Pass 1 of the algorithm.
How many comparisons and swaps occurred?
Bubble sort compares adjacent pairs left to right. If left > right,
swap. After one pass the largest value is at the end. Repeat,
ignoring the last sorted element each time.
Start: [3, 1, 4, 1, 5] Compare 3,1 → swap → [1, 3, 4, 1, 5] Compare 3,4 → no swap Compare 4,1 → swap → [1, 3, 1, 4, 5] Compare 4,5 → no swap After Pass 1: [1, 3, 1, 4, 5] Comparisons: 4 Swaps: 2
13
Reading and writing text files
Programs often need to save data permanently. Python uses
open()
with a mode: "r" = read, "w" = write
(overwrites), "a" = append. The
with
statement closes the file automatically.
# Writing to a file ("w" = write mode — creates or overwrites) with open("scores.txt", "w") as f: # Opens file, auto-closes when done f.write("Alice,92\n") # \n = newline character f.write("Bob,78\n") f.write("Charlie,85\n") # Reading from a file with open("scores.txt", "r") as f: # "r" = read mode content = f.read() # Read entire file as one string print(content) # Reading line by line with open("scores.txt", "r") as f: for line in f: # Loop through each line line = line.strip() # Remove \n whitespace parts = line.split(",") # Split on comma: ["Alice", "92"] name, score = parts[0], int(parts[1]) print(f"{name}: {score}") # Appending to a file (adds without deleting existing content) with open("scores.txt", "a") as f: # "a" = append mode f.write("Diana,95\n") # Added to end of file
14
Project A — Password Strength Checker
Combines strings, loops, selection and functions. Checks if a
password meets security criteria and gives a strength rating — a
real-world application of Year 7–9 Python skills.
def check_password(password): """Return a strength score and feedback for a password.""" score = 0 feedback = [] # Check length if len(password) >= 12: score += 2 elif len(password) >= 8: score += 1 else: feedback.append("Use at least 8 characters") # Check for uppercase letters has_upper = any(c.isupper() for c in password) if has_upper: score += 1 else: feedback.append("Add uppercase letters (A–Z)") # Check for digits has_digit = any(c.isdigit() for c in password) if has_digit: score += 1 else: feedback.append("Add digits (0–9)") # Check for symbols symbols = "!@#$%^&*()_-+=[]{}|;:,.<>?" has_symbol = any(c in symbols for c in password) if has_symbol: score += 2 else: feedback.append("Add symbols (!@#$ etc)") # Determine strength label if score >= 5: strength = "🔒 Strong" elif score >= 3: strength = "⚠️ Medium" else: strength = "❌ Weak" return strength, feedback # Main program pwd = input("Enter a password to check: ") strength, tips = check_password(pwd) print(f"\nStrength: {strength}") if tips: print("Suggestions:") for tip in tips: print(f" • {tip}")
15
Project B — Caesar Cipher (Encryption)
Uses ASCII values, modular arithmetic and functions to
encrypt/decrypt messages. This is a real encryption technique that
links directly to the cybersecurity and data topics in Years 8 and
9.
def caesar(text, shift, encode=True): """Encode or decode text using Caesar cipher.""" if not encode: # Decoding = reverse shift shift = -shift result = "" for ch in text: if ch.isalpha(): # Only shift letters base = ord('A') if ch.isupper() else ord('a') # ord() gives ASCII number; chr() converts back to character # % 26 wraps around the alphabet (z → a) result += chr((ord(ch) - base + shift) % 26 + base) else: result += ch # Spaces and punctuation unchanged return result # Demo msg = "Hello World" encoded = caesar(msg, 3) decoded = caesar(encoded, 3, encode=False) print(f"Original : {msg}") # Hello World print(f"Encrypted: {encoded}") # Khoor Zruog print(f"Decrypted: {decoded}") # Hello World
🌐
Year 9 · Web Authoring
HTML — Complete Reference Guide
HTML (HyperText Markup Language) is the language used to build web pages. Every snippet below is explained tag by tag, attribute by attribute — exactly like the Python section. Work through them in order: each one builds on the last.
H1
The HTML boilerplate — what every file must begin with
A boilerplate is the minimum required code that
every HTML document must have. Without these lines, the browser
guesses what you mean — and often guesses wrong. Think of it as
the frame you always start with before adding your content.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My Page Title</title> </head> <body> <!-- ALL your visible content goes in here --> </body> </html>
| Line | What it is | Why it matters |
|---|---|---|
<!DOCTYPE html> |
Document Type Declaration | Tells the browser "this is HTML5". Without it, the browser enters "quirks mode" and may render your page incorrectly. Must be the very first line — nothing above it. |
<html lang="en"> |
Root element |
The outermost tag that wraps everything.
lang="en" tells screen readers and search engines the
page is in English. All other tags live inside this one.
|
<head> |
Head section | Contains information about the page — not visible to visitors. The browser reads this first to set up the page before displaying anything. |
<meta charset="UTF-8"> |
Character encoding | UTF-8 supports every character in every language — including accented letters (é, ñ), currency symbols (€, £) and emojis. Without this, special characters display as garbled symbols. |
<meta name="viewport" ...> |
Viewport meta tag |
Makes the page responsive on mobile. Without this, phones zoom out
and show a tiny desktop version. width=device-width =
use the screen's actual width. initial-scale=1.0 =
start at 100% zoom.
|
<title> |
Page title | The text shown in the browser tab and in Google search results. Every page should have a unique, descriptive title. Does NOT appear on the page itself. |
<body> |
Body section | Everything visible on the page goes here — headings, paragraphs, images, links, tables. The browser renders this for the user. |
</html> |
Closing root tag |
Every tag that was opened must be closed.
</html> is the last line of every HTML file.
|
Opening vs Closing tags: Most tags come in pairs —
<tag> opens and </tag> closes.
The forward slash / means "close". Content goes between them:
<h1>My Title</h1>. Some tags are
self-closing and need no closing tag:
<meta>, <br>,
<hr>, <img>.
✏️ Try It Yourself
Q1. Create a new file called
index.html. Add the
boilerplate and give the page the title "Year 9 Portfolio". What do
you see in the browser tab?
Q2. What is wrong with this code?
<html><body><h1>Hello</body></html>
Look carefully at the h1 tag — what is missing at the end?
<!-- Q2: The <h1> tag is never closed. Should be: --> <h1>Hello</h1> <!-- Also missing: !DOCTYPE, head, charset, viewport, title -->
H2
Everything that can go inside the <head> section
The
<head>
is invisible to the reader but it is where you configure the page
for the browser, search engines and mobile devices. It can link to
external stylesheets, scripts, fonts and more.
<head> <!-- 1. CHARACTER ENCODING — always first inside head --> <meta charset="UTF-8"> <!-- 2. VIEWPORT — makes page responsive on phones/tablets --> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- 3. PAGE TITLE — shown in browser tab and Google results --> <title>TheShelf — Year 9 Computing</title> <!-- 4. DESCRIPTION — appears under your link in Google --> <meta name="description" content="Year 9 computing revision resources"> <!-- 5. AUTHOR --> <meta name="author" content="Alice Johnson"> <!-- 6. LINK TO EXTERNAL CSS FILE --> <link rel="stylesheet" href="style.css"> <!-- 7. LINK TO EXTERNAL JAVASCRIPT FILE --> <script src="script.js" defer></script> <!-- 8. GOOGLE FONT --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link href="https://fonts.googleapis.com/css2?family=Inter&display=swap" rel="stylesheet"> </head>
| Tag / Attribute | Type | Detailed Explanation |
|---|---|---|
<meta charset="UTF-8"> |
Self-closing meta | UTF-8 is a character encoding standard that covers 143,000+ characters from 154 languages. Without it, typing £ might show as †or similar. |
name="viewport" |
Meta — viewport | Without this tag, a phone browser assumes the page is 980px wide (desktop) and zooms out. This tag tells it to use the actual screen width. |
<title> |
Paired tag | Displays in the browser tab, bookmarks, history, and as the blue clickable link in Google. Keep it under 60 characters. |
name="description" |
Meta — SEO | The 1–2 sentence summary shown under your link in search results. Does not affect ranking but affects clicks. |
<link rel="stylesheet"> |
Self-closing link |
Links an external CSS file. rel="stylesheet" tells
the browser the file type. href is the path.
|
<script defer> |
Script tag |
Loads an external JavaScript file. defer tells the
browser to download in background and run after HTML is parsed.
|
✏️ Try It Yourself
Q1. What is the difference between
<title>
and
name="description"? Where does each one appear?
Q2. Why should you use
defer
on your script tag?
<title> shows in the browser TAB and as the blue link in
Google. The description meta appears as grey summary text below the
link. defer means the JS downloads in parallel but only runs after
HTML is ready.
<!-- Q1: <title> appears in the browser TAB. Description appears in Google results.
Neither appears on the actual webpage itself.
Q2: Without defer, the browser stops loading HTML to run the script, making the page feel slow.
defer downloads JS in the background and runs it after HTML is ready. -->
H3a
Headings <h1> to <h6> — the six levels
Headings create a hierarchy — like chapters and sections in a
book.
<h1>
is the biggest (main page title).
<h6>
is the smallest.
<h1>Main Page Title — The Biggest Heading</h1> <h2>Section Heading — Like a Chapter Title</h2> <h3>Sub-section — Heading inside a chapter</h3> <h4>Smaller sub-section</h4> <h5>Rarely used — very small heading</h5> <h6>Smallest heading level</h6>
| Tag | Visual size | Rule / Best Practice |
|---|---|---|
<h1> |
Largest | Use ONLY ONCE per page — it is the main title. |
<h2> |
Large | Use for major sections. |
<h3> |
Medium | Subsections inside an h2. Never skip levels. |
H3b
Paragraphs, line breaks and text formatting
Paragraphs are blocks of text. HTML ignores extra spaces and line
breaks in your code — use tags instead. Formatting tags like
<strong>
and
<em>
add meaning as well as visual style.
<!-- PARAGRAPH — creates a block of text with space above and below --> <p>This is a paragraph of text. Even if you put lots of spaces or line breaks in the code, the browser ignores them.</p> <!-- LINE BREAK — forces a new line within the same paragraph --> <p> Line one of this paragraph.<br> Line two — still the same paragraph, just a new line. </p> <!-- HORIZONTAL RULE — a full-width dividing line --> <hr> <!-- TEXT FORMATTING TAGS --> <p> <strong>Bold — important text</strong><br> <em>Italic — emphasised text</em><br> <u>Underlined text</u><br> <mark>Highlighted text — yellow background</mark><br> <code>print("Hello")</code> — monospace font for code </p>
Don't use <br> for spacing! A common mistake
is stacking
<br> tags to add space. That's bad
practice. Use CSS margin or
padding instead.
✏️ Try It Yourself
Q1. Write HTML to display: a heading "Online Safety", then a
paragraph with the word "important" in bold and "cyberbullying" in
italic.
Use <h2> for the heading. Wrap important words in
<strong> and key terms in <em>.
<h2>Online Safety</h2> <p>It is <strong>important</strong> to understand what <em>cyberbullying</em> means online.</p>
H4a
Hyperlinks — the <a> tag in every variation
The
<a>
(anchor) tag creates a hyperlink. The
href
attribute tells the browser where to go.
<!-- 1. EXTERNAL LINK --> <a href="https://www.bbc.co.uk">Visit the BBC website</a> <!-- 2. OPEN IN NEW TAB --> <a href="https://www.google.com" target="_blank">Google (new tab)</a> <!-- 3. ANCHOR LINK — jumps to a section on the SAME page --> <a href="#contact-section">Jump to Contact</a> <!-- The section it jumps to needs a matching id: --> <h2 id="contact-section">Contact Us</h2> <!-- 4. EMAIL LINK --> <a href="mailto:[email protected]">Email us</a>
| Attribute | Value | Explanation |
|---|---|---|
href |
"https://..." |
HyperText REFerence — the destination URL. |
target="_blank" |
"_blank" |
Opens the link in a new browser tab. |
href="#id" |
Anchor (#) |
Jumps to the element with that id on the same page.
|
H4b
Images — the <img> tag, attributes and file paths
The
<img>
tag is self-closing. The
src
and
alt
attributes are both required.
<!-- BASIC IMAGE --> <img src="logo.png" alt="TheShelf school logo"> <!-- IMAGE WITH SIZE --> <img src="profile.jpg" alt="A smiling student" width="300" height="200"> <!-- CLICKABLE IMAGE — wrap <img> inside <a> --> <a href="https://www.bbc.co.uk"> <img src="bbc-logo.png" alt="Go to BBC"> </a>
| Attribute | Required? | Explanation |
|---|---|---|
src |
Yes | Source — the path or URL of the image file. |
alt |
Yes | Alternative text — describes the image for screen readers and if the image fails to load. |
width |
Recommended | Width in pixels. |
Never leave alt empty unless the image is purely
decorative. Empty alt on meaningful images fails accessibility
standards.
✏️ Try It Yourself
Write an image tag for a file called
avatar.png in an
images/ folder, 150px wide, with a proper alt
description.
src="images/avatar.png" points to a subfolder. Add width="150" on
the img tag.
<img src="images/avatar.png" alt="Profile photo of the website author" width="150">
H5a
Unordered and ordered lists
<ul>
(unordered) gives bullet points.
<ol>
(ordered) gives numbers. Both use
<li>
for each list item.
<!-- UNORDERED LIST — bullet points --> <ul> <li>Online Safety</li> <li>Binary Numbers</li> <li>Python Programming</li> </ul> <!-- ORDERED LIST — numbered --> <ol> <li>Open your IDE</li> <li>Write your Python code</li> <li>Run and test the program</li> </ol>
H5b
Tables — rows, columns, headers
Tables organise data into rows and columns. Use them for data that
genuinely belongs in a grid — like a spreadsheet of results.
<table> <tr> <th>Name</th> <th>Score</th> <th>Grade</th> </tr> <tr> <td>Alice</td> <td>92</td> <td>A</td> </tr> <tr> <td>Bob</td> <td>78</td> <td>B</td> </tr> </table>
| Tag | Stands for | Explanation |
|---|---|---|
<table> |
Table | The outer container. |
<tr> |
Table Row | Creates one horizontal row. |
<th> |
Table Header | A header cell — bold and centred by default. |
<td> |
Table Data | A regular data cell. |
✏️ Try It Yourself
Build a table showing the binary values 128, 64, 32, 16, 8, 4, 2, 1
in the first row, and 1, 0, 1, 1, 0, 0, 1, 1 in the second row (the
binary for 179).
Use <table>, <tr> for rows, <th> for header cells,
<td> for data cells. First row: eight <th> tags.
<table>
<tr>
<th>128</th><th>64</th><th>32</th><th>16</th>
<th>8</th><th>4</th><th>2</th><th>1</th>
</tr>
<tr>
<td>1</td><td>0</td><td>1</td><td>1</td>
<td>0</td><td>0</td><td>1</td><td>1</td>
</tr>
</table>
H6
Every form element explained
HTML forms collect information from users. The
type
attribute on
<input>
controls exactly what kind of data the user can enter.
<form action="submit.php" method="post"> <!-- TEXT INPUT --> <label for="fname">First Name:</label> <input type="text" id="fname" name="firstname" required> <!-- EMAIL --> <label for="email">Email:</label> <input type="email" id="email" name="email" required> <!-- PASSWORD --> <label for="pwd">Password:</label> <input type="password" id="pwd" name="password"> <!-- RADIO BUTTONS — pick exactly ONE option --> <p>Select your year group:</p> <input type="radio" name="year" value="7" id="y7"> <label for="y7">Year 7</label> <input type="radio" name="year" value="8" id="y8"> <label for="y8">Year 8</label> <!-- DROPDOWN SELECT --> <label for="subject">Favourite subject:</label> <select name="subject" id="subject"> <option value="">-- Please choose --</option> <option value="computing">Computing</option> <option value="maths">Maths</option> </select> <!-- BUTTONS --> <button type="submit">Submit Form</button> </form>
| Attribute | Purpose |
|---|---|
type="text" |
Single-line text input. |
type="password" |
Characters are masked as dots. |
type="radio" |
All radio buttons with the SAME name form a group —
only one can be selected.
|
required |
Prevents form submission if this field is empty. |
H7
Semantic HTML5 tags
Semantic means "meaningful". Semantic tags tell
the browser AND screen readers what role each part of the page
plays.
<header> <h1>TheShelf — Computing Resources</h1> </header> <nav> <a href="index.html">Home</a> <a href="year7.html">Year 7</a> </nav> <main> <section id="binary"> <h2>Binary Numbers</h2> <p>Binary uses only 0s and 1s...</p> </section> </main> <footer> <p>© 2025 TheShelf.</p> </footer>
| Tag | Where it goes | Explanation |
|---|---|---|
<header> |
Top of page | Contains introductory content — site logo, site name. |
<nav> |
Inside header | Groups all navigation links. |
<main> |
Central area | Contains the unique primary content. ONLY ONE per page. |
<section> |
Inside main | Groups related content into a thematic block. |
<footer> |
Bottom of page | Contains closing information — copyright, contact links. |
Semantic tags improve three things: (1)
Accessibility — screen readers navigate by
landmarks. (2) SEO — Google understands your
content structure. (3) Readability — other
developers understand the layout instantly.
H8
Three ways to add CSS
CSS (Cascading Style Sheets) controls colours, fonts, sizes,
spacing, layout — everything visual. The key CSS properties every
exam requires are annotated below.
<!-- INLINE CSS — style directly on one tag --> <h1 style="color: navy; text-align: center;">Blue Centred Heading</h1> <!-- INTERNAL <style> BLOCK — inside <head> --> <style> body { font-family: Arial, sans-serif; background-color: #f0f4f8; color: #333333; } h1 { color: darkblue; font-size: 2em; text-align: center; } </style> <!-- EXTERNAL CSS FILE — linked in <head> --> <link rel="stylesheet" href="style.css">
| CSS Property | Values | What it does |
|---|---|---|
color |
red, #ff0000 |
Sets the text colour. |
background-color |
lightblue |
Sets the background colour. |
font-size |
16px, 1.2em |
Text size. px = fixed. em = relative. |
padding |
10px |
Space INSIDE the element, between content and border. |
margin |
20px auto |
Space OUTSIDE the element. auto centres block
elements.
|
border |
2px solid black |
Width · style · colour. |
✏️ Try It Yourself
Write CSS to make all <h2> tags dark green, 24px, and centred.
Target an element with its tag (h2 { }). color sets text colour,
font-size sets size, text-align: center centres it.
h2 {
color: darkgreen;
font-size: 24px;
text-align: center;
}
H9
A complete, valid HTML5 portfolio page
This is the type of page you will build for your Year 9 web
authoring project. It uses every major concept:
boilerplate · head metadata · semantic tags · headings ·
paragraphs · lists · a table · a form · images · links · internal
CSS.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Alice Johnson — Computing Portfolio</title> <style> * { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: Arial, sans-serif; background: #f0f4f8; color: #222; } header { background: #003366; color: white; padding: 30px 40px; } nav { background: #002244; padding: 12px 40px; } nav a { color: #aac8ff; text-decoration: none; margin-right: 20px; } main { max-width: 900px; margin: 30px auto; padding: 0 20px; } section { margin-bottom: 40px; } footer { background: #222; color: #aaa; text-align: center; padding: 20px; } </style> </head> <body> <header> <h1>Alice Johnson</h1> <p>Year 9 Computing Portfolio</p> </header> <nav> <a href="#about">About</a> <a href="#projects">Projects</a> </nav> <main> <section id="about"> <h2>About Me</h2> <p>I am a Year 9 student passionate about computing.</p> </section> </main> <footer> <p>© 2025 Alice Johnson</p> </footer> </body> </html>
This is exam-ready HTML. Copy it, save as
portfolio.html, open in any browser. Customise the
content, add your own photo, change the colour scheme in the
CSS.