This content can't be printed from the browser. Use Export PDF with Pro for an offline copy.
IB Syllabus Requirements for Programming fundamentals
B2.1.1
Variables, data types and scope
B2.1.2
Extracting and manipulating substrings
B2.1.3
Handling exceptions
B2.1.4
Finding and correcting bugs
B2.1.1
VARIABLES, DATA TYPES AND SCOPE
Constructing a program means choosing suitable variables and operations; tracing it means following execution and recording how its values change. A correct trace follows the instructions actually written, not what the programmer intended.
A variable associates a name with a value that a program can use or change. Its data type determines the kind of value it represents and which operations are appropriate.
| Data type | What it represents | Java | Python |
|---|---|---|---|
| Boolean value | Either true or false | boolean, for example true | bool, for example True |
| char | One character | char, for example 'R' | No separate character type: use a one-character str |
| decimal | A number with a fractional part | Commonly double, for example 1.5 | Commonly float, for example 1.5 |
| integer | A whole number | int, for example 2 | int, for example 2 |
| string | A sequence of characters | String, for example "Repair" | str, for example "Repair" |
Java declarations specify types explicitly. Python associates a type with the assigned value, so assigning an integer does not require writing a type declaration. A digit stored in a string is text, not automatically a number on which arithmetic can be performed.
Scope is the region of a program in which a name can be accessed. A global variable is available across functions in its enclosing program or module; a local variable belongs to a particular function, method or block.
In Python, a variable defined at module level is global. A function can read it without a special declaration; assigning to that global name from inside the function requires the global declaration. Prefer local variables when a value does not need to be shared, because this limits unintended changes elsewhere.
Java has no free-standing global variables. A class-level static field provides shared state for the methods in that class. Variables declared inside a method are local to that method, and variables declared inside a block are restricted to that block.
fee from the local values count, category, label, active and total. The calculation reads the shared value but does not change it.
A repair desk calculates a total from two units charged at 1.5 each. The program uses all five required data types and prints Repair R 3.0.
Java
1 public class RepairCharge {
2 static double fee = 1.5;
3 static void showCharge() {
4 int count = 2;
5 char category = 'R';
6 String label = "Repair";
7 boolean active = true;
8 double total = count * fee;
9 if (active) {
10 System.out.println(label + " " + category + " " + total);
11 }
12 }
13 public static void main(String[] args) {
14 showCharge();
15 }
16 }
Python
1 fee = 1.5
2 def show_charge():
3 count = 2
4 category = 'R'
5 label = "Repair"
6 active = True
7 total = count * fee
8 if active:
9 print(label + " " + category + " " + str(total))
10 show_charge()
Python needs an explicit string conversion for total when concatenating it with strings. Java performs that conversion as part of string concatenation.
A dash means that the variable has not yet received a value. The local variables cease to be accessible when the method or function returns.
| Event | fee | count | category | label | active | total | Output |
|---|---|---|---|---|---|---|---|
| Shared value assigned | 1.5 | — | — | — | — | — | — |
| Assign count | 1.5 | 2 | — | — | — | — | — |
| Assign category | 1.5 | 2 | R | — | — | — | — |
| Assign label | 1.5 | 2 | R | Repair | — | — | — |
| Assign active | 1.5 | 2 | R | Repair | true | — | — |
| Calculate total | 1.5 | 2 | R | Repair | true | 3.0 | — |
| Condition is true; print | 1.5 | 2 | R | Repair | true | 3.0 | Repair R 3.0 |
Terms to use: global variables, local variables, data types, Boolean value, char, decimal, integer, string, construct, trace.
B2.1.2
EXTRACTING AND MANIPULATING SUBSTRINGS
To construct a substring-processing program, first identify the character positions to extract, then apply the required changes and assemble the result. Check the boundaries separately from the manipulation: an incorrect starting position can produce plausible but wrong text.
A substring is a contiguous sequence of characters within a string. String positions are indexed from zero in both Java and Python.
For BX-417-ready, the identifier 417 occupies indices 3, 4 and 5. The status ready starts at index 7 and continues to the end of the string.
| Operation | Java | Python |
|---|---|---|
| Extract from start index up to, but excluding, end index | substring() with start and end arguments | A slice with start and end positions |
| Extract from a start index to the end | substring() with one argument | A slice with the end omitted |
| Join strings | String concatenation using + | String concatenation using + |
| Replace matching text | replace() | replace() |
| Convert letters to uppercase | toUpperCase() | upper() |
For the identifier, use start index 3 and end index 6: the start is included, but the end is excluded. The extracted length is therefore 6 − 3 = 3 characters.
BX-417-ready: extracting 417, altering ready to READY, and concatenating these pieces into Parcel 417: READY. A separate replacement produces BX-417-held.
Strings are immutable in both languages: these operations produce new strings rather than modifying individual characters in the existing string. Assign the returned value to a variable if it is needed later.
Java
1 public class ParcelLabel {
2 public static void main(String[] args) {
3 String text = "BX-417-ready";
4 String identifier = text.substring(3, 6);
5 String status = text.substring(7);
6 status = status.toUpperCase();
7 String result = "Parcel " + identifier + ": " + status;
8 String updated = text.replace("ready", "held");
9 System.out.println(result);
10 System.out.println(updated);
11 }
12 }
Python
1 text = "BX-417-ready"
2 identifier = text[3:6]
3 status = text[7:]
4 status = status.upper()
5 result = "Parcel " + identifier + ": " + status
6 updated = text.replace("ready", "held")
7 print(result)
8 print(updated)
The original text remains BX-417-ready throughout. In particular, replacing text to create updated does not change text or the previously constructed result.
| Event | text | identifier | status | result | updated | Output |
|---|---|---|---|---|---|---|
| Assign original | BX-417-ready | — | — | — | — | — |
| Extract identifier | BX-417-ready | 417 | — | — | — | — |
| Extract status | BX-417-ready | 417 | ready | — | — | — |
| Alter status | BX-417-ready | 417 | READY | — | — | — |
| Concatenate result | BX-417-ready | 417 | READY | Parcel 417: READY | — | — |
| Replace text | BX-417-ready | 417 | READY | Parcel 417: READY | BX-417-held | — |
| Print result | BX-417-ready | 417 | READY | Parcel 417: READY | BX-417-held | Parcel 417: READY |
| Print updated | BX-417-ready | 417 | READY | Parcel 417: READY | BX-417-held | BX-417-held |
Terms to use: strings, substrings, extract, manipulate, altering, concatenating, replacing.
B2.1.3
HANDLING EXCEPTIONS
Programs use exception handling to respond deliberately when an operation fails during execution. Describe both the possible failure and how control moves to a handler rather than continuing normally through the failed operation.
An exception signals a failure during execution that interrupts the normal sequence of instructions. Exception handling provides a controlled route for responding to such a failure.
| Potential point of failure | Example | Appropriate response |
|---|---|---|
| Unexpected inputs | Text such as many is supplied where a whole number is needed | Validate the input and handle a failed conversion |
| Resource unavailability | A required file cannot be opened or a service cannot be reached | Handle the access failure, report the problem or use an appropriate alternative |
| Logic errors | A calculation subtracts a charge when it should add it | Locate and correct the faulty reasoning; use tests to check the result |
A logic error does not necessarily raise an exception. A program can finish normally and still produce the wrong answer. Exception handling therefore supports reliability, but it does not replace input validation, testing or debugging.
The try block contains operations that may fail. Java uses catch to handle a matching exception; Python uses except. If an exception occurs, the remaining instructions in that try block are skipped and execution moves to a matching handler.
The finally block runs after the attempt, whether the operation succeeds or a handled exception occurs. It is used for actions that should happen on either route, such as cleanup. After a handled failure and its finally block, execution can continue after the whole construct.
try leads directly to finally on success, or through catch / except on a matching failure. Both routes then reach continuation.
Handle exception types that the program can respond to meaningfully. A handler that silently ignores every failure can conceal defects and leave the program in an unsuitable state.
These programs attempt to convert many to an integer. The conversion fails, so the normal output inside try is skipped. The handler prints Enter a whole number, and finally prints Attempt finished.
Java
1 public class SeatInput {
2 public static void main(String[] args) {
3 String supplied = "many";
4 try {
5 int seats = Integer.parseInt(supplied);
6 System.out.println(seats);
7 } catch (NumberFormatException error) {
8 System.out.println("Enter a whole number");
9 } finally {
10 System.out.println("Attempt finished");
11 }
12 }
13 }
Python
1 supplied = "many"
2 try:
3 seats = int(supplied)
4 print(seats)
5 except ValueError:
6 print("Enter a whole number")
7 finally:
8 print("Attempt finished")
The failed conversion never assigns a value to seats. Java signals NumberFormatException; Python signals ValueError.
| Event | supplied | seats | Output |
|---|---|---|---|
| Assign input text | many | Not assigned | — |
| Attempt conversion; exception raised | many | Not assigned | — |
| Matching handler runs | many | Not assigned | Enter a whole number |
| Finally block runs | many | Not assigned | Attempt finished |
If the input text were 4, the conversion would succeed, the handler would be skipped, and the output would be 4 followed by Attempt finished.
Terms to use: unexpected inputs, resource unavailability, logic errors, exception handling, try/catch, try/except, finally block.
B2.1.4
FINDING AND CORRECTING BUGS
Use debugging techniques to find the first point where a program's behaviour differs from its intended behaviour, then correct the cause and run it again. A useful debugging record connects an observed value to the instruction that produced it.
Debugging is the process of locating and correcting faults in a program. The following techniques expose different aspects of execution; other techniques also exist.
| Technique | How to use it | What it reveals |
|---|---|---|
| Trace tables | Execute instructions manually and record changes to variables and output | The exact sequence of calculated values |
| Print statements | Temporarily display selected values at important points | What the running program actually contains at those points |
| Breakpoint debugging | Pause execution at a chosen line and inspect the program state | Values immediately before a suspicious instruction executes |
| Step-by-step code execution | Execute one instruction at a time while watching values | The instruction where behaviour first diverges from the intention |
A trace table can be prepared without running the program. Print statements reveal values during a real run, but too many can make the output difficult to follow. Breakpoints and stepping allow inspection without inserting temporary output instructions.
A delivery counter should combine a base quantity of 8 with an extra quantity of 3. The expected total is 11, but a faulty version subtracts the extra quantity and produces 5. Tracing the calculation identifies subtraction as the cause; the correction is to use addition.
The paired programs below contain the corrected calculation and a temporary print statement before it. That first output checks the inputs; the second checks the result.
Java
1 public class DeliveryTotal {
2 public static void main(String[] args) {
3 int base = 8;
4 int extra = 3;
5 System.out.println(base + " " + extra);
6 int total = base + extra;
7 System.out.println(total);
8 }
9 }
Python
1 base = 8
2 extra = 3
3 print(base, extra)
4 total = base + extra
5 print(total)
6 # Remove the temporary input print after checking.
| Event | base | extra | total | Output |
|---|---|---|---|---|
| Assign base | 8 | — | — | — |
| Assign extra | 8 | 3 | — | — |
| Print inputs | 8 | 3 | — | 8 3 |
| Calculate total | 8 | 3 | 11 | — |
| Print result | 8 | 3 | 11 | 11 |
For breakpoint debugging, pause before Java line 6 or Python line 4. Inspect base and extra, then step over the calculation and inspect total. In the faulty version, this would expose the change to 5 at the calculation itself, rather than merely showing an incorrect final output.
Once the calculation is correct, remove the temporary input print and run the program again. Also check other suitable inputs: one successful run confirms that run, not every possible case.
Terms to use: debugging techniques, trace tables, breakpoint debugging, print statements, step-by-step code execution.