Counting loops
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
Words and a number on one line
- A comma inside
printputs a space between the parts. print("7 x", 1, "=", 7 * 1)prints7 x 1 = 7.+cannot join a number to text. Use the comma, or turn the number into text withstr.
Common mistakes
range(n)counts0ton - 1, not1ton.range(a, b)stops beforeb.- The loop body must be indented under the
forline.
Now you try
- Use a
forloop withrange(...)in each task. - Press Check answer to test your code.
A counting loop, pass by pass
A for loop repeats its body; watch the counter and the running total.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Use a for loop to print the numbers 1 to 5, each on its own line.
Click Run to see the output here.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
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.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
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.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Print exactly one line: 7 x 1 = 7. Finish the print that is already started. A comma between the parts prints them with spaces: print("7 x", 1, "=", 7 * 1).
Click Run to see the output here.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Use a for loop to print the first five lines of the 7 times table: 7 x 1 = 7, 7 x 2 = 14, up to 7 x 5 = 35. The print from the last task is already inside the loop — change the 1 into the loop variable.
Click Run to see the output here.