← Back to Hub
Computer Science XII · 13 Chapters · 75+ syntax items

Syntax & Commands Reference

Python syntax, SQL commands, and networking concepts — organised by chapter for quick revision.

01 Exception Handling in Python 8 marks
raise syntax
raise ExceptionType('error message')
ExceptionType can be any built-in or user-defined exception class
assert syntax
assert condition, 'error message'
If condition is False, AssertionError is raised with the optional message
try-except basic syntax
try: # statements that may raise exception except ExceptionType: # handler code
The except block executes only if the specified exception occurs in the try block
Multiple except clauses
try: # statements except ValueError: # handle ValueError except ZeroDivisionError: # handle ZeroDivisionError
Each except clause handles a different type of exception
try-except-else syntax
try: # statements except ExceptionType: # handle exception else: # runs only if no exception occurred
The else block is optional and runs when try succeeds without any exception
try-except-finally syntax
try: # statements except ExceptionType: # handle exception finally: # always executes (cleanup code)
The finally block is guaranteed to execute in all circumstances
Complete try block syntax
try: # risky code except ExceptionType: # handle error else: # no exception occurred finally: # cleanup — always runs
This is the most complete form of exception handling in Python
02 File Handling in Python 16 marks
open() syntax
file_object = open(filename, mode)
Default mode is 'r'. Returns a file object (file handle).
close() syntax
file_object.close()
Flushes any unwritten data and closes the file. Good practice to always close files.
with statement syntax
with open('filename', 'mode') as file_object: # file operations
Automatically closes the file when the with block is exited
write() syntax
file_object.write(string)
Returns the number of characters written. Does not add newline automatically.
writelines() syntax
file_object.writelines(list_of_strings)
Writes each string from the list. No newline added between strings.
read() syntax
content = file_object.read([size])
Without argument, reads the entire file. With size, reads at most that many characters.
readline() syntax
line = file_object.readline()
Reads one line including newline. Returns empty string '' at EOF.
readlines() syntax
lines = file_object.readlines()
Returns a list of all lines. Each line includes the trailing newline character.
tell() syntax
position = file_object.tell()
Returns an integer representing the current position of the file pointer in bytes
seek() syntax
file_object.seek(offset, reference_point)
reference_point: 0 = beginning (default), 1 = current, 2 = end. For text files, only 0 is allowed as reference_point.
pickle.dump() syntax
import pickle pickle.dump(object, file_object)
file_object must be opened in binary write mode ('wb' or 'ab')
pickle.load() syntax
import pickle object = pickle.load(file_object)
file_object must be opened in binary read mode ('rb'). Raises EOFError when no more objects to read.
03 Stack 16 marks
PUSH algorithm
Step 1: If stack is full, print 'Overflow' and return Step 2: Increment TOP by 1 Step 3: Set stack[TOP] = element Step 4: Return
In Python using list, we use append() which handles resizing automatically
POP algorithm
Step 1: If stack is empty, print 'Underflow' and return Step 2: Set element = stack[TOP] Step 3: Decrement TOP by 1 Step 4: Return element
In Python using list, we use pop() which removes and returns the last element
Stack implementation using list
stack = [] # empty stack stack.append(element) # PUSH element = stack.pop() # POP top = stack[-1] # PEEK len(stack) # SIZE len(stack) == 0 # isEmpty
Python lists grow dynamically, so no overflow check needed for list-based stacks
Operator precedence (highest to lowest)
** (exponentiation) > *, /, //, % > +, -
** is right-associative; all others are left-associative
Infix to Postfix conversion examples
A + B -> A B + A + B * C -> A B C * + (A + B) * C -> A B + C * A + B * C - D -> A B C * + D - (A + B) * (C - D) -> A B + C D - *
Follow operator precedence and associativity rules during conversion
Infix to Postfix Algorithm
1. Create an empty stack and output list 2. Scan the infix expression left to right: a. If operand, add to output b. If '(', push onto stack c. If ')', pop and add to output until '(' is found; discard '(' d. If operator, pop and add to output while stack top has >= precedence (for left-assoc) or > precedence (for right-assoc); then push current operator 3. Pop all remaining operators from stack to output
Handle operator associativity: left-to-right for +, -, *, /; right-to-left for **
Postfix Evaluation Algorithm
1. Create an empty stack 2. Scan the postfix expression left to right: a. If operand, push onto stack b. If operator, pop two operands (op2 = pop, op1 = pop), compute op1 operator op2, push result 3. The final element in the stack is the result
op1 is the second popped element, op2 is the first popped. Order: op1 operator op2.
04 Queue Supplementary
Enqueue algorithm
Step 1: If queue is full, print 'Overflow' and return Step 2: Increment rear by 1 Step 3: Set queue[rear] = element Step 4: If front is -1, set front = 0 Step 5: Return
In Python using list, we use append() which adds to the end automatically
Dequeue algorithm
Step 1: If queue is empty, print 'Underflow' and return Step 2: Set element = queue[front] Step 3: Increment front by 1 Step 4: If front > rear, reset front = rear = -1 (queue empty) Step 5: Return element
In Python using list, we use pop(0) which removes the first element
Queue implementation using list
queue = [] # empty queue queue.append(element) # Enqueue element = queue.pop(0) # Dequeue front = queue[0] # Peek len(queue) # Size len(queue) == 0 # isEmpty
pop(0) is O(n) — for better performance, use collections.deque
Deque implementation using list
deque = [] # empty deque deque.append(element) # Add at rear deque.insert(0, element) # Add at front element = deque.pop() # Remove from rear element = deque.pop(0) # Remove from front
insert(0, elem) and pop(0) are O(n). For O(1), use collections.deque with appendleft() and popleft()
05 Sorting Supplementary
Bubble Sort Time Complexity (Worst/Average)
O(n^2)
Occurs when the array is sorted in reverse order. Total comparisons = n(n-1)/2.
Bubble Sort Time Complexity (Best Case)
O(n)
Occurs when the array is already sorted (with optimized version using a flag). Only one pass with n-1 comparisons and no swaps.
Bubble Sort Space Complexity
O(1)
In-place sorting algorithm; only requires a temporary variable for swapping.
Total Comparisons (Worst Case)
(n-1) + (n-2) + ... + 1 = n(n-1)/2
In pass i, the number of comparisons is (n - i).
Selection Sort Time Complexity (All Cases)
O(n^2)
Always performs n(n-1)/2 comparisons regardless of input order. Best, worst, and average cases are all O(n^2).
Selection Sort Space Complexity
O(1)
In-place sorting algorithm.
Maximum Number of Swaps
n - 1
At most one swap per pass, making it efficient when swapping is costly.
Insertion Sort Time Complexity (Worst Case)
O(n^2)
Occurs when the array is sorted in reverse order. Total comparisons and shifts = n(n-1)/2.
Insertion Sort Time Complexity (Best Case)
O(n)
Occurs when the array is already sorted. Only n-1 comparisons and no shifts needed.
Insertion Sort Time Complexity (Average Case)
O(n^2)
On average, each insertion requires shifting half of the sorted portion.
Insertion Sort Space Complexity
O(1)
In-place sorting algorithm; only needs a variable to hold the key.
Constant Time
O(1)
Time does not depend on input size. Example: accessing an array element by index.
Logarithmic Time
$O(\log n)$
Time grows logarithmically. Example: Binary Search.
Linear Time
O(n)
Time grows linearly with input size. Example: Linear Search.
Quadratic Time
O(n^2)
Time grows quadratically. Example: Bubble Sort, Selection Sort, Insertion Sort (worst case).
06 Searching Supplementary
Linear Search Time Complexity (Best Case)
O(1)
Element is found at the first position. Only 1 comparison needed.
Linear Search Time Complexity (Worst Case)
O(n)
Element is at the last position or not present. All n elements are compared.
Linear Search Time Complexity (Average Case)
O(n)
On average, n/2 comparisons are needed. Still linear.
Linear Search Space Complexity
O(1)
Only a few variables are used regardless of input size.
Binary Search Time Complexity (Best Case)
O(1)
Element is found at the middle position in the first comparison.
Binary Search Time Complexity (Worst Case)
$O(\log_2 n)$
Maximum number of comparisons is floor(log2(n)) + 1. The search space halves each time.
Binary Search Time Complexity (Average Case)
$O(\log_2 n)$
On average, approximately log2(n) comparisons are needed.
Binary Search Space Complexity (Iterative)
O(1)
Iterative version uses constant extra space.
Middle Element Index
mid = (low + high) // 2
low is the start index and high is the end index of the current search range.
Common Hash Function (Division Method)
h(key) = key \% table\_size
The modulo operation ensures the hash value falls within the valid index range [0, table_size - 1].
Hashing Time Complexity (Average Case)
O(1)
Average-case search, insert, and delete are constant time with a good hash function.
Hashing Time Complexity (Worst Case)
O(n)
Worst case occurs when all keys hash to the same index (all collisions).
07 Understanding Data Supplementary
Mean (Arithmetic Mean)
$\bar{x} = \frac{\sum_{i=1}^{n} x_i}{n} = \frac{x_1 + x_2 + ... + x_n}{n}$
Sum of all values divided by the count of values.
Median (Odd n)
$Median = x_{(n+1)/2}$
Middle value when n is odd and data is sorted.
Median (Even n)
$Median = \frac{x_{n/2} + x_{(n/2)+1}}{2}$
Average of two middle values when n is even and data is sorted.
Range
$Range = x_{max} - x_{min}$
Difference between the largest and smallest values.
Variance (Population)
$\sigma^2 = \frac{\sum_{i=1}^{n} (x_i - \bar{x})^2}{n}$
Average of squared deviations from the mean. Uses n in the denominator for population variance.
Variance (Sample)
$s^2 = \frac{\sum_{i=1}^{n} (x_i - \bar{x})^2}{n - 1}$
Uses (n-1) in the denominator to provide an unbiased estimate.
Standard Deviation
$\sigma = \sqrt{\frac{\sum_{i=1}^{n} (x_i - \bar{x})^2}{n}}$
Square root of variance. Expressed in the same units as the data.
08 Database Concepts 5 marks
No standalone syntax items
This chapter focuses on conceptual understanding. See Chapters page for key points.
09 Structured Query Language (SQL) 15 marks
COUNT
SELECT COUNT(*) FROM table_name;
COUNT(*) counts all rows. COUNT(column) counts non-NULL values.
SUM
SELECT SUM(column) FROM table_name;
Returns the total of all values in the column. NULL values are ignored.
AVG
SELECT AVG(column) FROM table_name;
Returns the average. NULL values are excluded from the calculation.
MAX and MIN
SELECT MAX(column), MIN(column) FROM table_name;
Returns the largest and smallest values respectively.
Cartesian Product Size
$Rows = m \times n, \; Columns = p + q$
If table A has m rows and p columns, table B has n rows and q columns.
10 Computer Networks 5 marks
Number of links in Mesh Topology
Number of links = n(n-1)/2, where n is the number of devices
Each device has (n-1) ports. For example, 5 devices need 5(4)/2 = 10 links.
Number of ports per device in Mesh
Ports per device = n - 1
Each device must have (n-1) I/O ports to connect to every other device.
Total IPv4 Addresses
2^32 = 4,294,967,296 (approximately 4.3 billion)
32-bit address space, each octet ranges from 0 to 255
Total IPv6 Addresses
2^128 = approximately 3.4 x 10^38
128-bit address space, providing virtually unlimited addresses
11 Data Communication 5 marks
Data Transfer Rate Units
1 Kbps = 1,024 bps (or 10^3 bps); 1 Mbps = 1,024 Kbps (or 10^6 bps); 1 Gbps = 1,024 Mbps (or 10^9 bps); 1 Tbps = 1,024 Gbps (or 10^12 bps)
bps = bits per second, Kbps = Kilobits per second, Mbps = Megabits per second, Gbps = Gigabits per second, Tbps = Terabits per second
Time to transfer data
Time = File Size (in bits) / Data Transfer Rate (in bps)
Remember to convert file size from bytes to bits (multiply by 8) if given in bytes
12 Security Aspects Supplementary
No standalone syntax items
This chapter focuses on conceptual understanding. See Chapters page for key points.
13 Project Based Learning Supplementary
No standalone syntax items
This chapter focuses on conceptual understanding. See Chapters page for key points.