Use built-in functions and library routines

Programming Basics – Built‑in Functions & Library Routines (Cambridge IGCSE/A‑Level 9618)

1. Quick‑Reference Overview

  • Built‑in functions: Always available, no import required. Used for fundamental I/O, type conversion and simple sequence handling.
  • Library routines: Belong to a module (Python) or package (Java). Must be imported before use and are accessed via a namespace.
  • Control structures, procedures & functions, exception handling are all required for AO1–AO3.
  • Additional AS‑level topics that must be linked to programming:

    • Data‑type declarations, arrays, records, files, ADTs (stack/queue/linked list)
    • Number systems, binary/hexadecimal conversion, bit manipulation
    • Logic‑gate truth tables
    • Security, ethics & privacy
    • Basic hardware/processor concepts


2. Built‑in Functions

These functions are part of the core language and require no import statement.

PythonPseudocode (Cambridge)JavaVisual Basic
print(...)OUTPUT ...System.out.println(...);Console.WriteLine(...)
input()READ ...new Scanner(System.in).nextLine();Console.ReadLine()
len(seq)SIZE(seq)seq.length (arrays) / list.size()seq.Length
range(start, stop, step)FOR i ← start TO stop‑1 STEP stepfor (int i = start; i < stop; i += step) { … }For i As Integer = start To stop - 1 Step step
type(obj)no direct equivalent – use documentationobj.getClass()obj.GetType()
int(x), float(x), str(x)INTEGER(x), REAL(x), STRING(x)(int) x, (double) x, String.valueOf(x)CInt(x), CDbl(x), CStr(x)
abs(x), pow(x, y)ABS(x), POWER(x, y)Math.abs(x), Math.pow(x,y)Math.Abs(x), Math.Pow(x,y)
sum(iterable)SUM(seq)IntStream.of(arr).sum()Enumerable.Sum(seq)

2.1 Number Systems & Bit Manipulation (AS 1.1 & 4.3)

  • Binary (base‑2), Decimal (base‑10) and Hexadecimal (base‑16) are the three systems examined.
  • Conversion examples:

    # Decimal → Binary

    bin(13) # '0b1101'

    # Binary → Decimal

    int('1101', 2) # 13

    # Decimal → Hex

    hex(255) # '0xff'

    # Hex → Decimal

    int('FF', 16) # 255

  • Simple bit‑wise operations (required for AS 4.3):

    # Left shift (multiply by 2ⁿ)

    x = 5 # 0b0101

    x << 2 # 0b010100 = 20

    # Right shift (integer division by 2ⁿ)

    x >> 1 # 0b0010 = 2

    # Bitwise AND, OR, XOR

    a & b # 0b0100

    a | b # 0b0111

    a ^ b # 0b0011

2.2 Logic‑Gate Truth Tables (AS 3.2)

GateSymbolTruth Table
AND&
A B | A∧B

0 0 | 0

0 1 | 0

1 0 | 0

1 1 | 1

OR
A B | A∨B

0 0 | 0

0 1 | 1

1 0 | 1

1 1 | 1

NOT¬
A | ¬A

0 | 1

1 | 0

XOR
A B | A⊕B

0 0 | 0

0 1 | 1

1 0 | 1

1 1 | 0


3. Library Routines (Modules / Packages)

Library routines live inside a module (Python) or package (Java). They must be imported before use.

3.1 Common Standard‑Library Modules (Python)

  • math – advanced mathematics, constants (π, e).
  • random – pseudo‑random number generation.
  • sys – interpreter parameters, command‑line arguments.
  • os – file‑system and OS interaction.
  • datetime – dates, times, timedeltas.
  • io – low‑level stream handling (open, read, write, close).

3.2 Import Styles

  • import math – use as math.sqrt(...)
  • from math import sqrt, pi – use directly as sqrt(...)
  • import math as m – use as m.sqrt(...)

Exam tip: Avoid import * – it obscures the namespace and can cause name clashes.

3.3 Example: Using math and random

# math – area of a circle

import math

r = 5

area = math.pi * math.pow(r, 2)

print("Area =", area)

# random – roll a die

import random

die = random.randint(1, 6) # inclusive

print("Die roll:", die)

3.4 File‑handling (Built‑ins + io module)

# Write numbers to a file

with open('numbers.txt', 'w') as f:

for n in [12, 7, 5]:

f.write(str(n) + '\n')

# Read back and compute the mean

total = 0

count = 0

with open('numbers.txt', 'r') as f:

for line in f:

total += int(line.strip())

count += 1

mean = total / count

print('Mean =', mean)

3.5 Exception Handling (Python, Java, Visual Basic)

try:

f = open('data.txt', 'r')

data = f.read()

except FileNotFoundError:

print('File not found – please check the filename.')

finally:

f.close()

LanguageTry‑Catch Syntax
Java
try {

// code that may throw an exception

} catch (FileNotFoundException e) {

System.out.println("File not found");

} finally {

// optional clean‑up code

}

Visual Basic
Try

' code that may raise an error

Catch ex As IOException

Console.WriteLine("File not found")

Finally

' clean‑up code

End Try


4. Control Structures – Cheat‑Sheet (AO2 & AO3)

StructurePythonPseudocode (Cambridge)JavaVisual Basic
Count‑controlled loopfor i in range(start, stop, step):FOR i ← start TO stop‑1 STEP stepfor (int i = start; i < stop; i += step) { … }For i As Integer = start To stop - 1 Step step
Pre‑condition loopwhile condition:WHILE condition DOwhile (condition) { … }Do While condition
Post‑condition loopwhile True:

if not condition: break

REPEAT … UNTIL NOT conditiondo { … } while (condition);Do … Loop While condition
IF … ELSE IF … ELSEif cond1:

elif cond2:

else:

IF cond1 THEN …

ELSE IF cond2 THEN …

ELSE …

ENDIF

if (cond1) { … } else if (cond2) { … } else { … }If cond1 Then … ElseIf cond2 Then … Else … End If
CASE (select) statementmatch expr:

case 1: …

case 2: …

case _: …

CASE expr OF

1: …

2: …

OTHERWISE …

switch (expr) { case 1: … break; … default: … }Select Case expr

Case 1

Case 2

Case Else

End Select

4.1 Algorithmic Complexity (AO2)

When choosing a loop or data‑structure, note its time‑complexity:

  • Linear scan – O(n) – suitable for small‑to‑medium lists.
  • Binary search – O(log n) – requires a sorted array; faster for large data sets.
  • Stack/Queue operations – O(1) for push/pop or enqueue/dequeue.

In exam answers, a brief comment such as “linear time, O(n)” earns marks for justification.


5. Structured Programming – Procedures, Functions & ADTs

5.1 Definitions (Cambridge terminology)

  • Procedure – performs an action, no return value (returns None in Python).
  • Function – computes a value and returns it with return.
  • ADT (Abstract Data Type) – a logical description of a data structure (stack, queue, linked list) together with the operations that can be performed on it.

5.2 Python Examples

# Procedure – prints a greeting

def greet(name):

print("Hello, " + name)

# Function – factorial (recursive)

def factorial(n):

if n == 0:

return 1

return n * factorial(n-1)

# Simple stack ADT using a list

class Stack:

def init(self):

self._data = [] # private list

def push(self, item):

self._data.append(item)

def pop(self):

if not self._data:

raise IndexError("pop from empty stack")

return self._data.pop()

def is_empty(self):

return len(self._data) == 0

5.3 Pseudocode Equivalents

PROCEDURE Greet(name)

OUTPUT "Hello, " + name

END PROCEDURE

FUNCTION Factorial(n) RETURNS INTEGER

IF n = 0 THEN

RETURN 1

ELSE

RETURN n * Factorial(n-1)

END IF

END FUNCTION

TYPE Stack

data : ARRAY[0..99] OF INTEGER // simple fixed‑size array

top : INTEGER := -1

END TYPE

PROCEDURE Push(s : INOUT Stack, value : INTEGER)

s.top ← s.top + 1

s.data[s.top] ← value

END PROCEDURE

FUNCTION Pop(s : INOUT Stack) RETURNS INTEGER

IF s.top = -1 THEN

ERROR "Stack underflow"

END IF

value ← s.data[s.top]

s.top ← s.top - 1

RETURN value

END FUNCTION

5.4 Java / Visual Basic Sketches

LanguageProcedure (void)Function (returns value)ADT (stack)
Java
public static void greet(String name) {

System.out.println("Hello, " + name);

}

public static int factorial(int n) {

if (n == 0) return 1;

return n * factorial(n-1);

}

public class Stack {

private int[] data = new int[100];

private int top = -1;

public void push(int v) {

data[++top] = v;

}

public int pop() {

if (top < 0) throw new EmptyStackException();

return data[top--];

}

public boolean isEmpty() {

return top == -1;

}

}

Visual Basic
Sub Greet(name As String)

Console.WriteLine("Hello, " & name)

End Sub

Function Factorial(n As Integer) As Integer

If n = 0 Then

Return 1

Else

Return n * Factorial(n - 1)

End If

End Function

Structure Stack

Private data(99) As Integer

Private top As Integer = -1

End Structure

Sub Push(ByRef s As Stack, ByVal v As Integer)

s.top += 1

s.data(s.top) = v

End Sub

Function Pop(ByRef s As Stack) As Integer

If s.top = -1 Then Throw New InvalidOperationException("underflow")

Dim v As Integer = s.data(s.top)

s.top -= 1

Return v

End Function

5.5 Quick‑Reference: Arrays, Records, Files & ADTs

ConceptPythonJavaVisual BasicPseudocode (Cambridge)
Array (fixed size)arr = [0]*10 # list used as arrayint[] arr = new int[10];Dim arr(9) As IntegerARRAY arr[0..9] OF INTEGER
Record / Structureclass Person: pass # simple classclass Person { String name; int age; }Structure Person

name As String

age As Integer

End Structure

RECORD Person

name : STRING

age : INTEGER

END RECORD

File (sequential text)with open('file.txt','r') as f: …BufferedReader br = new BufferedReader(new FileReader("file.txt"));Dim sr As New StreamReader("file.txt")OPEN "file.txt" FOR INPUT AS #1

CLOSE #1

Stack ADTlist.append(x) / list.pop()java.util.Stack<Integer> s = new Stack<>();Dim s As New Stack(Of Integer)PROCEDURE Push(s : INOUT Stack, v : INTEGER)
Queue ADTfrom collections import deque; q = deque(); q.append(x); q.popleft()java.util.Queue<Integer> q = new LinkedList<>();Dim q As New Queue(Of Integer)PROCEDURE Enqueue(q : INOUT Queue, v : INTEGER)


6. Software Development Life‑Cycle (SDLC) & Testing

6.1 Typical SDLC Models (Cambridge focus)

  • Waterfall – sequential: requirements → design → implementation → testing → maintenance.
  • Iterative / Incremental – develop a small part, test, then refine.
  • Rapid Application Development (RAD) – quick prototype → feedback → improvement.

6.2 Testing Checklist (Paper 4 – programming)

  1. Syntax check – code compiles / runs without errors.
  2. Logical check – algorithm follows the specification.
  3. Boundary testing – test minimum, maximum and typical values.
  4. Exception testing – verify handling of error conditions (e.g., file not found, division by zero).
  5. Black‑box testing – test against the specification without looking at the code.
  6. White‑box testing – examine all code paths, loops and conditionals for full coverage.
  7. Complexity justification – note the time‑complexity (O(n), O(log n), etc.) when relevant.

6.3 Security, Ethics & Privacy (AS 7)


7. Basic Hardware & Processor Recap (AS 3.1 & 3.2)

  • CPU cycle – Fetch → Decode → Execute → Store.
  • Registers – small, fast storage inside the CPU (e.g., accumulator, program counter).
  • ALU – performs arithmetic and logical operations (add, subtract, AND, OR, NOT).
  • Memory hierarchy – registers → cache → main RAM → secondary storage.
  • Parallel processing (A‑level) – multiple cores execute instructions simultaneously; concepts of threads and synchronization are introduced later.


8. Comparison – Built‑in Functions vs. Library Routines

AspectBuilt‑in FunctionLibrary Routine
AvailabilityAlways available; no import required.Must import the module/package first.
Typical UseBasic I/O, type conversion, simple sequence operations, elementary maths (e.g., abs, pow).Specialised tasks – advanced maths, random numbers, file I/O, system interaction, date‑time handling, data structures.
NamespaceGlobal namespace.Accessed via module.function or from module import ….
PerformanceVery fast – no module lookup.Slight overhead for import and lookup, negligible for exam‑level programs.
DocumentationLanguage reference.Module API guide (e.g., math).


9. Best Practices for Exams (Paper 2 & Paper 4)

  1. Prefer built‑in functions for simple tasks – they keep code short and are less error‑prone.
  2. Import only the modules you need; avoid import *.
  3. Use explicit imports (from math import sqrt, pi) when you need only a few routines.
  4. When writing pseudocode, replace Python built‑ins with the Cambridge equivalents shown in the mapping tables.
  5. Include basic error handling for I/O and conversion operations (try/except or try/catch).
  6. Comment briefly to show logical structure – markers look for clarity.
  7. Test with at least three different input sets, including edge cases and invalid data.
  8. State the algorithmic complexity where relevant (e.g., “linear scan – O(n)”).
  9. Remember security/ethics reminders – a short comment on data validation or confidentiality can earn marks.


10. Typical Exam Questions (Paper 2 & Paper 4)

  • Write a program that reads a list of integers, stores them in an array/list, and prints the mean using sum() and len() (built‑ins).
  • Explain the difference between math.pow(x, y) and the exponentiation operator x**y. Include a short example.
  • Given a scenario that requires random selection of a quiz question, choose an appropriate function from the random module, justify your choice and show the code.
  • Design a procedure called saveData that writes a list of strings to a file called output.txt. Show both the Python implementation and the equivalent pseudocode.
  • Write a try/except block that attempts to open a file called data.txt. If the file does not exist, output “File not found”. Include a finally clause that closes the file.
  • Implement a simple stack ADT with push, pop and isEmpty operations. Provide Python code and the corresponding Cambridge pseudocode.
  • Discuss the time‑complexity of scanning an array to find the maximum value versus using a binary search on a sorted array.


11. Key Take‑aways

  • Built‑in functions are always available and ideal for fundamental tasks such as I/O, type conversion and simple sequence operations.
  • Library routines extend the language; they must be imported and are accessed via a module namespace.
  • Control structures, procedures, functions and ADTs are core to structured programming and are examined across AO1–AO3.
  • Understanding number systems, bit manipulation and logic gates satisfies the AS‑level hardware and data‑representation requirements.
  • Security, ethics and privacy considerations are part of the syllabus – a brief comment in code demonstrates awareness.
  • Clear, well‑commented code, appropriate use of built‑ins, and a short justification of algorithmic choices earn maximum marks.