SLIDE 1
CSZone.co.uk
Click to advance · Arrow keys also work
Edexcel 1CP2 · Topic 6 · 6.1d

Iteration:
for & while Loops

range() · Nested Loops · break · Accumulators · Trace Tables

CSZoneEdexcel GCSE Computer Science 1CP2
for Loops in Depth

Definite Iteration

# range(start, stop, step)
for i in range(1, 11, 2): # 1,3,5,7,9
print(i)

# Iterate over a string
for char in "Hello":
print(char) # H e l l o
range(stop): 0 to stop-1; range(start,stop): start to stop-1; range(start,stop,step): with step
for loops work with any iterable: strings, lists, ranges — not just numbers
while Loops & Accumulators

Indefinite Iteration & Totals

total = 0
count = 0
while count < 5:
num = int(input("Enter number: "))
total += num # accumulator
count += 1
print("Total:", total)
print("Average:", total / 5)
An accumulator is a variable that collects a running total using +=
Infinite loop: if the condition never becomes False, the loop runs forever — always make sure the counter updates
Nested Loops & break

Loops Inside Loops

for row in range(3):
for col in range(3):
print(row, col) # 9 combinations

# break exits the loop immediately
for i in range(10):
if i == 5:
break
print(i) # 0 1 2 3 4
Nested loops: the inner loop completes fully for each iteration of the outer loop
break: exits the loop; continue: skips the rest of the current iteration and moves to the next
Exam Practice

Have a go at this question

Edexcel-style question
Trace the output of this code:

total = 0
for i in range(1, 5):
total += i
print(total)
2 marks
range(1,5) gives 1,2,3,4 [1]. total = 0+1+2+3+4 = 10. Output: 10 [1].
Key Takeaways

What to Remember

for: definite (known count); range(start,stop,step) — stop is exclusive
while: condition-controlled; must update the counter or condition or risk infinite loop
Accumulator: total += value — common pattern for summing inputs
Nested loops: inner completes fully each outer iteration; break exits loop immediately