Iteration — loops
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Count-controlled loops
- Iteration means repeating steps.
- A count-controlled loop repeats a fixed number of times.
- In Python that is
for i in range(n):.
for i in range(5):
print("Hello")
Choosing the range
range(5)gives0, 1, 2, 3, 4.range(1, 6)gives1, 2, 3, 4, 5— it stops before 6.range(2, 11, 2)counts in steps of 2.
for n in range(1, 6):
print(n)
Pre-condition loops: while
- A pre-condition loop tests before each pass.
- It may run zero times if the test is false at the start.
count = 0
while count < 5:
print(count)
count = count + 1
Post-condition loops: REPEAT UNTIL
- A post-condition loop tests after each pass, so it always runs at least once.
- Python has no
repeat, so we usewhile Truewithbreak.
total = 0
while True:
total = total + 1
if total >= 3:
break
print(total)
Explore
Each pass changes count
A loop repeats its body; count must change so the test finally fails.
In the exam: FOR, WHILE, REPEAT
- Pseudocode has all three loop types.
FOR i ← 1 TO 5
OUTPUT i
NEXT i
Common mistakes
- A
forloop repeats a known number of times; awhilerepeats until something changes. range(n)runs0ton - 1.- Change the condition inside a
while, or it never ends.
Now you try
- Pick the loop that fits each task.
- Press Check answer to test your code.
Use a for loop to print the numbers 1 to 5, one on each line.
Click Run to see the output here.
Use a loop to add up the numbers 1 to 10, then print the total (it is 55).
Click Run to see the output here.
Read a whole number n, then count down from n to 1, one per line. For input 3, print 3, 2, 1.
Click Run to see the output here.