B2.3.3 Repeating with loops
SL + HLCommand term: Construct1. 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.
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(,,): 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.
>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.
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.
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.
8. 45-second speed round: how many passes?
How many times does the loop body run?
continue and break. The commands list stands in for what the librarian types, so the tests can run without input().Expected output
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
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.
- Open your PyCharm project (or New Project → pure Python, name it
ib_cs_tasks). - Right-click the project → New → Python File, using the file name shown on the task.
- Press Copy starter and paste it in, or press Download .py.
- Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
- Replace each
pass # your code herewith your own code. Do not change the code below# ---- tests ----. - Run the file and compare your output with Expected output. A crash or an
AssertionErrormeans something is not right yet. - Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
- Written parts: answer in your notebook first, then check the model answer.
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):
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
Model solution
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))
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):
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
Model solution
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)))
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):
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
Model solution
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:
- Distinguish between counted and conditional loops, and choose the appropriate type for a task.
- Construct counted loops with
forandrange(start, stop, step), and loops that traverse collections, in Python and Java. - Construct conditional loops with
while(and Java's do-while), including sentinel and input-validation loops. - Use selection with Boolean and relational operators inside loops, and
breakandcontinue, to govern how a loop executes. - 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 loop | Conditional loop | |
|---|---|---|
| Repeats | A known number of times, or once per item | While a condition is True (until something happens) |
| Python | for i in range(5): / for book in catalogue: | while choice != "q": |
| Java | for (int i = 0; i < 5; i++) / for (String b : books) | while (...) { } and do { } while (...); |
| Use for | Every item in a list, every day of the week, a fixed number of tries | Menus, input validation, waiting, searching until found |
| Risk | Off-by-one errors in range | Infinite 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]
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]
5. Explain why a while loop is more appropriate than a for loop for the ShelfWise main menu. [2]
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]
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].