Counting loops
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Repeat with for
- A
forloop repeats code a fixed number of times. - The body of the loop is indented, like an
if. - A loop variable holds a new value on each pass.
Counting with range
range(5)gives the numbers0, 1, 2, 3, 4(stops before 5).range(1, 6)gives1, 2, 3, 4, 5(start included, stop not).range(0, 10, 2)counts in steps of 2.
for i in range(5):
print(i)
Build a total (accumulator)
- An accumulator is a variable that grows inside a loop.
- Start it at
0before the loop. - Add to it on each pass to build a running total.
total = 0
for n in range(1, 6):
total = total + n
print(total)
In Cambridge pseudocode
- A Python
for … rangeloop is the exam's count-controlledFOR … NEXT.
total ← 0
FOR i ← 1 TO 5
total ← total + i
NEXT i
OUTPUT total
Now you try
- Use a
forloop withrange(...)in each task. - Press Check answer to test your code.
Use a for loop to print the numbers 1 to 5, each on its own line.
Click Run to see the output here.
Use a loop and an accumulator to add up every whole number from 1 to 100. Store the total in total.
Click Run to see the output here.
Multiply together every whole number from 1 to 5 (that is 1×2×3×4×5). Start product at 1 and store the result there.
Click Run to see the output here.