IB Computer Science HL · Year 2 · Lesson 5

Loops, Functions, Modularization and Strings

Construct Python solutions that combine substring manipulation, repetition, functions, modularization and scope.

Paper 250 minutesB2.1.2 · B2.3.3 · B2.3.4
Today’s targets

What you need to be able to do

2 / 10
  • construct programs that extract and manipulate substrings;
  • choose and construct counted and conditional loops appropriately;
  • use Boolean or relational conditions within loops;
  • construct reusable functions with inputs and return values;
  • explain how modularization and local/global scope support maintainable programs.
B2.1.2B2.3.3B2.3.4
Paper 2 habitRead the command term and the data given. A technically correct answer still needs to answer the exact task.
Learn + retrieve

Rapid Recall Deck

3 / 10

Attempt each card first. If a term is new, flip and study it, then answer it again without looking. Mark only secure recall as “Know it”.

B2.1.2 · Construct

Extract and manipulate substrings

4 / 10
code = "IBCS-HL-2027"

subject = code[0:4]
level = code[5:7]
year = code[8:12]

display = subject + " " + level + " " + year
updated = code.replace("HL", "SL")
Manipulation vocabulary: the display statement uses concatenation to join string parts, while replace() alters part of the original string.

Trace, then construct

Trace — state the values of subject, level, year, display and updated.
Construct — write one expression that extracts 2027 and one expression that produces "IBCS/HL/2027".

Trace: subject = "IBCS", level = "HL", year = "2027", display = "IBCS HL 2027", updated = "IBCS-SL-2027".

Possible constructions:

code[8:12]
code.replace("-", "/")
B2.3.3 · Loops

Counted or conditional?

5 / 10

Counted loop

for i in range(5):
    print(i)

Use when the repetitions are known or can be generated from a count/range.

Conditional loop

attempts = 0
while attempts < 3:
    print("Try")
    attempts += 1

Use when repetition continues while a condition remains True.

Choose the appropriate loop

Scenario A processes exactly 30 sensor readings. Scenario B repeatedly asks for a password until it is correct or three attempts have been used.

Scenario A — choose counted or conditional and justify.
Scenario B — choose counted or conditional and state what condition should control repetition.

A: a counted loop is natural because exactly 30 readings must be processed. B: a conditional loop is natural because repetition depends on whether the password is still incorrect and attempts remain, for example while not correct and attempts < 3.

Loop conditions

Selection inside repetition

6 / 10
scores = [72, 41, 88, 59, 95]
passes = 0

for score in scores:
    if score >= 60 and score <= 100:
        passes += 1

print(passes)

Trace the loop

State the value of passes after each score is processed and the final printed output.

Track one variable — passes.
Apply both relational tests joined by and.

After 72 → 1; after 41 → 1; after 88 → 2; after 59 → 2; after 95 → 3. Final output: 3.

B2.3.4 · Functions

Modularize a repeated task

7 / 10
ProblemA program needs to calculate a percentage in several different places. Copying the same formula repeatedly makes later changes harder to manage.

Construct a reusable function

Write percentage(part, whole) so it returns 0 when whole == 0; otherwise it returns the percentage value.

Inputs — part and whole.
Selection — handle the zero denominator.
Return — send the result back to the caller.
def percentage(part, whole):
    if whole == 0:
        return 0
    return (part / whole) * 100
Why modularize?A single well-named function can be tested once, reused in multiple places and updated without editing every duplicate formula.
Scope

Trace local and global variables

8 / 10
tax_rate = 0.08

def total_with_tax(price):
    tax = price * tax_rate
    total = price + tax
    return total

answer = total_with_tax(50)
print(answer)

Trace the call

Global — identify variables available outside the function.
Local during the call — identify price, tax and total values.
Output — state the printed result.

Globals: tax_rate = 0.08 and, after the call, answer = 54.0. Locals: price = 50, tax = 4.0, total = 54.0. The program prints 54.0.

Integrated construct

Combine strings, loops and functions

9 / 10
RequirementGiven codes = ["IBCS-HL-2027", "IBDT-SL-2027", "IBCS-SL-2027"], return how many codes begin with the substring "IBCS". Do not use count().

Construct count_ibcs(codes)

Function — receive the List as an input.
Loop — traverse every code.
Substring test — compare code[0:4] with "IBCS".
Local counter — update and return it.
def count_ibcs(codes):
    count = 0
    for code in codes:
        if code[0:4] == "IBCS":
            count += 1
    return count

For the given data, the function returns 2.

Homework

Finish the learning cycle

10 / 10

IA — main task

Refine IA Criterion B/C planning so repeated tasks are decomposed into clear modules or functions where appropriate. Do not force modularization where it does not fit the solution.

Syllabus — short retrieval

Redo the integrated function on page 9 without Reveal, then change it so it counts codes ending in "2027".