Home › Theme B › B2 › B2.3 › B2.3.3

B2.3.3 Repeating with loops

SL + HLCommand term: Construct

1. Watch a loop run

Step through three loops. The trace table fills in as each pass completes. Notice how a counted loop knows its number of passes in advance, while a conditional loop keeps going until its condition changes.

Loop:

2. range() explorer

A Python counted loop usually uses range(start, stop, step). The stop value is never included. Change the numbers and see the values the loop variable takes, and the same loop in Java.

for i in range(,,):
Values:
Java:

3. ShelfWise menu loop: a live console

This is a real conditional loop with break and continue. Type commands: l to list, s dune to search, a blank line, anything invalid, and q to quit. The highlighted lines are the ones that ran on the last pass.

>
pass = 0   count = 0   loop running: True
Type a command.

4. Nested loops on the shelves

The shelves are a 2D list: 3 shelves, 4 slots each. An outer loop visits each shelf, an inner loop each slot. Pick a task to see a condition inside the loop change what happens.

Task:
shelf = -   slot = -   inner passes = 0
Choose a task and press Run.

5. Python and Java loops

Click a row to compare. Java has a do-while loop, which always runs at least once; Python does not.

Click a row.

6. Flip-card deck

Click to flip. Say the answer before you flip.

7. Counted or conditional?

Which kind of loop fits the job? Streaks of 3+ score double.

Round 0/10Score 0Streak 0Best 0
Press start!

8. 45-second speed round: how many passes?

How many times does the loop body run?

Time 45sScore 0Streak 0Best 0
Press start!
ShelfWise · Sprint 3, task 3. ShelfWise becomes a program that keeps running. Write counted loops to list, search and report, a validation loop that gives up after three tries, and the main menu loop with continue and break. The commands list stands in for what the librarian types, so the tests can run without input().

Expected output

1. Dune (2) 2. Emma (0) 3. Holes (4) 4. Dracula (1) Found: Dune No match Overdue: 3 Fines: 11.5 Invalid: 7 Invalid: x Invalid: 0 Invalid: 9 Invalid: abc 2 None 1. Dune (2) 2. Emma (0) 3. Holes (4) 4. Dracula (1) Found: Emma Invalid choice Goodbye

Make it interactive

When the tests pass, write run_live(): the same menu, but with while True: and cmd = input("> ") at the top of the loop instead of a list of commands. Which loop type did you need this time, and why could run(commands) use a counted loop?

Check my code

    Next task (B2.3.4): split ShelfWise into well-named functions and modules, with parameters, return values and local scope.

    Practical tasks

    Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.

    Set up in PyCharm
    1. Open your PyCharm project (or New Project → pure Python, name it ib_cs_tasks).
    2. Right-click the project → New → Python File, using the file name shown on the task.
    3. Press Copy starter and paste it in, or press Download .py.
    4. Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
    How the tasks work
    1. Replace each pass # your code here with your own code. Do not change the code below # ---- tests ----.
    2. Run the file and compare your output with Expected output. A crash or an AssertionError means something is not right yet.
    3. Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
    4. Written parts: answer in your notebook first, then check the model answer.
    Average

    Task 1: Sum of multiples

    Write sum_multiples(limit, a, b) that adds every number below limit that is a multiple of a or b. Use a for loop. Then write the same with a while loop.

    Starter file (write your code where it says pass # your code here):

    File: b2_3_3_average.py
    def sum_multiples(limit, a, b):
        pass  # your code here
    
    def sum_multiples_while(limit, a, b):
        pass  # your code here
    
    # ---- tests ----
    print(sum_multiples(10, 3, 5), sum_multiples_while(10, 3, 5))
    print(sum_multiples(1000, 3, 5), sum_multiples_while(1000, 3, 5))
    

    Expected output when your code is correct:

    23 23
    233168 233168
    Hint
    Count each number once, even if it is a multiple of both.
    Model solution
    File: b2_3_3_average_solution.py
    def sum_multiples(limit, a, b):
        total = 0
        for n in range(limit):
            if n % a == 0 or n % b == 0:
                total += n
        return total
    
    def sum_multiples_while(limit, a, b):
        total = 0
        n = 0
        while n < limit:
            if n % a == 0 or n % b == 0:
                total += n
            n += 1
        return total
    
    # ---- tests ----
    print(sum_multiples(10, 3, 5), sum_multiples_while(10, 3, 5))
    print(sum_multiples(1000, 3, 5), sum_multiples_while(1000, 3, 5))
    
    Moderate

    Task 2: Primes with nested loops

    Write is_prime(n) that tests divisors only up to the square root of n, and primes_up_to(n) that returns a list of all primes up to n. Count how many primes there are below 10 000.

    Starter file (write your code where it says pass # your code here):

    File: b2_3_3_moderate.py
    def is_prime(n):
        pass  # your code here
    
    def primes_up_to(n):
        pass  # your code here
    
    # ---- tests ----
    print(primes_up_to(50))
    print(len(primes_up_to(10000)))
    

    Expected output when your code is correct:

    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
    1229
    Hint
    If n has a divisor bigger than its square root, it also has one smaller than it.
    Model solution
    File: b2_3_3_moderate_solution.py
    def is_prime(n):
        if n < 2:
            return False
        d = 2
        while d * d <= n:
            if n % d == 0:
                return False
            d += 1
        return True
    
    def primes_up_to(n):
        return [k for k in range(2, n + 1) if is_prime(k)]
    
    # ---- tests ----
    print(primes_up_to(50))
    print(len(primes_up_to(10000)))
    
    Challenging

    Task 3: Happy numbers

    Replace a number by the sum of the squares of its digits, and repeat. If you reach 1, the number is happy; otherwise it loops forever. Write next_n(n), is_happy(n) (detect the loop with a set of numbers already seen) and list the happy numbers up to 50.

    Starter file (write your code where it says pass # your code here):

    File: b2_3_3_challenging.py
    def next_n(n):
        pass  # your code here
    
    def is_happy(n):
        pass  # your code here
    
    # ---- tests ----
    print(next_n(19), next_n(82), next_n(68))
    print([n for n in range(1, 51) if is_happy(n)])
    

    Expected output when your code is correct:

    82 68 100
    [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49]
    Hint
    If a number appears for a second time, the sequence is in a loop.
    Model solution
    File: b2_3_3_challenging_solution.py
    def next_n(n):
        total = 0
        while n > 0:
            digit = n % 10
            total += digit * digit
            n //= 10
        return total
    
    def is_happy(n):
        seen = set()
        while n != 1 and n not in seen:
            seen.add(n)
            n = next_n(n)
        return n == 1
    
    # ---- tests ----
    print(next_n(19), next_n(82), next_n(68))
    print([n for n in range(1, 51) if is_happy(n)])
    

    Learning objectives

    By the end of this page you should be able to:

    1. Distinguish between counted and conditional loops, and choose the appropriate type for a task.
    2. Construct counted loops with for and range(start, stop, step), and loops that traverse collections, in Python and Java.
    3. Construct conditional loops with while (and Java's do-while), including sentinel and input-validation loops.
    4. Use selection with Boolean and relational operators inside loops, and break and continue, to govern how a loop executes.
    5. Trace loops, including nested loops, and predict how many times the body runs.

    Iteration

    A loop repeats a block of code (the loop body). Each repetition is a pass or iteration.

    Counted loopConditional loop
    RepeatsA known number of times, or once per itemWhile a condition is True (until something happens)
    Pythonfor i in range(5): / for book in catalogue:while choice != "q":
    Javafor (int i = 0; i < 5; i++) / for (String b : books)while (...) { } and do { } while (...);
    Use forEvery item in a list, every day of the week, a fixed number of triesMenus, input validation, waiting, searching until found
    RiskOff-by-one errors in rangeInfinite loop if the condition never becomes False (B2.3.1)

    range()

    • range(5) → 0, 1, 2, 3, 4 (five values, the stop is excluded).
    • range(1, 6) → 1 to 5. range(2, 11, 2) → 2, 4, 6, 8, 10. range(5, 0, -1) → 5, 4, 3, 2, 1.
    • If start has already passed stop in the direction of the step, the range is empty and the body never runs.

    Conditional loops: three patterns

    # 1. Sentinel loop: stop when a special value arrives
    title = input("Title (q to stop): ")
    while title != "q":
        print("Added", title)
        title = input("Title (q to stop): ")
    
    # 2. Validation loop: repeat until the input is acceptable
    choice = input("Choice 1-4: ")
    while not (choice.isdigit() and 1 <= int(choice) <= 4):
        choice = input("Please type 1, 2, 3 or 4: ")
    
    # 3. Menu loop: run until the user quits
    while True:
        cmd = input("> ")
        if cmd == "q":
            break                  # leave the loop at once
        ...

    Java's do-while tests its condition after the body, so the body always runs at least once: ideal for "show the menu, then ask". Python imitates it with while True: and a break at the end.

    Conditions inside loops

    • if inside a loop processes only some items: if copies == 0: count = count + 1.
    • break ends the loop immediately (for example, when a search finds its target). In nested loops it ends only the innermost loop.
    • continue skips the rest of this pass and goes straight to the next one (for example, skip blank lines or invalid data).
    • Compound conditions govern while loops: while tries < 3 and not valid: stops on success or after three tries.

    Nested loops

    A loop inside a loop: the inner loop runs completely for each pass of the outer loop, so 3 shelves × 4 slots = 12 inner passes. Used for 2D lists, tables and comparing every pair.

    Use the 中文 button at the top to show or hide the Chinese terms.

    Term中文Meaning

    Choose an answer. You get instant feedback.

    Score: 0 /

    Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.

    1. Distinguish between a counted loop and a conditional loop. [2]

    A counted loop repeats a fixed / predetermined number of times, e.g. for each item or for i in range(n) [1]; a conditional loop repeats while (or until) a condition is true, so the number of passes is not known in advance [1].

    2. Construct a Python loop that prints 10, 8, 6, 4, 2. [2]

    for i in range(10, 0, -2): [1] print(i) [1]. Accept range(10, 1, -2), or an equivalent while loop with initialisation and update.

    3. State the output. [3]

    for n in [4, 0, 7, -1, 9]:
        if n == 0:
            continue
        if n < 0:
            break
        print(n * 2)
    8 [1]; 0 is skipped by continue, then 14 [1]; -1 triggers break, so 9 is never processed [1].

    4. Construct a Python validation loop that keeps asking for a menu choice until the user types a whole number from 1 to 4. [4]

    Initial input before the loop (or while True) [1]; a while loop whose condition tests validity [1]: digits only and between 1 and 4, using relational operators combined with and [1]; input requested again inside the loop so the condition can change [1].

    5. Explain why a while loop is more appropriate than a for loop for the ShelfWise main menu. [2]

    The number of commands the librarian will enter is not known in advance [1]; the menu must keep repeating until a condition is met (the user chooses quit), which is what a conditional loop does [1].

    6. shelves is a 2D list of copy counts, e.g. [[2, 0, 1], [4, 0, 3]]. Construct code that counts how many slots have 0 copies, and the total number of copies. [4]

    Initialise both counters to 0 before the loops [1]; outer loop over the rows, inner loop over each value in the row [1]; if value == 0: increment the zero counter [1]; add value to the total, and print both after the loops (2 and 10 for the example) [1].