Loop patterns: sums, counting down and more
A loop on its own just repeats. Most real loops build up an answer one step at a time: a total, a count, a product. This lesson collects the patterns you'll meet in class and in exams, and traces each one so you can see exactly what happens.
Iteration: one trip round the loop
Each pass through a loop's body is called an iteration. The loop variable takes the next value on every iteration:
for i in range(1, 4):
print("Iteration number", i)
print("Loop finished")Writing out what happens, step by step, is called tracing the loop:
| Iteration | i | What runs |
|---|---|---|
| 1 | 1 | prints "Iteration number 1" |
| 2 | 2 | prints "Iteration number 2" |
| 3 | 3 | prints "Iteration number 3" |
| - | - | range(1, 4) has no more values, so the loop ends and "Loop finished" prints |
range(1, 4) gives 1, 2 and 3: it stops before its second number.
Adding up: the sum of 1 to 10
To add numbers with a loop you need a variable that holds the running total, called an accumulator. The pattern always has three parts:
total = 0 # 1. start the total at 0, BEFORE the loop
for i in range(1, 11): # 1, 2, ... 10 (11 is where range stops)
total = total + i # 2. add this number to the total
print("Sum of 1 to 10 =", total) # 3. use the total AFTER the looptotal = total + i is usually written total += i. The first few iterations:
| i | total before | total after |
|---|---|---|
| 1 | 0 | 1 |
| 2 | 1 | 3 |
| 3 | 3 | 6 |
| 4 | 6 | 10 |
| ... | ... | ... |
| 10 | 45 | 55 |
To watch the total grow, print inside the loop:
total = 0
for i in range(1, 11):
total += i
print(f"after adding {i}, the total is {total}")Counting down: 10 to 1 in reverse
range takes a third number, the step. A step of -1 counts backwards. The stop value is still left out, so to reach 1 you stop at 0:
for i in range(10, 0, -1):
print(i)
print("Lift off!")reversed(range(1, 11)) gives the same numbers and reads more clearly.
The sum of 1 to 10, in reverse
Adding from 10 down to 1 gives the same 55 (the order of addition doesn't matter), but the running totals are different:
total = 0
for i in range(10, 0, -1):
total += i
print(f"added {i}, total is {total}")
print("Sum of 10 down to 1 =", total)On one line
print ends with a new line unless you change its end:
for i in range(10, 0, -1):
print(i, end=" ")
print() # finish the lineThe same countdown with while:
n = 10
while n >= 1:
print(n)
n -= 1 # without this, n stays 10 and the loop never endsSums with a condition: even and odd numbers
i % 2 == 0 is true for even numbers (dividing by 2 leaves no remainder):
evens = 0
odds = 0
for i in range(1, 11):
if i % 2 == 0:
evens += i
else:
odds += i
print("Sum of even numbers:", evens)
print("Sum of odd numbers:", odds)Or skip the odd numbers entirely with a step of 2: sum(range(2, 11, 2)) is also 30.
Counting how many
A counter adds 1 each time something is true:
count = 0
for i in range(1, 101):
if i % 7 == 0:
count += 1
print(count, "numbers from 1 to 100 divide exactly by 7")Multiplying: the factorial
5! is 5 × 4 × 3 × 2 × 1. The accumulator for multiplying must start at 1: starting at 0 would make every answer 0.
n = 5
fact = 1
for i in range(1, n + 1):
fact *= i
print(f"{n}! = {fact}")Times tables
n = 7
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")Totals over a list: sum, average and largest
marks = [72, 85, 90, 64, 88]
total = 0
highest = marks[0]
for m in marks:
total += m
if m > highest:
highest = m
print("Total:", total)
print("Average:", total / len(marks))
print("Highest:", highest)
print("Built in:", sum(marks), max(marks))highest starts at the first mark, not 0: with negative numbers, 0 would win wrongly.
Taking a number apart: digit sum and reverse
n % 10 is the last digit and n // 10 drops it. Repeat until nothing is left:
n = 4096
digit_sum = 0
reversed_n = 0
while n > 0:
digit = n % 10 # the last digit
digit_sum += digit
reversed_n = reversed_n * 10 + digit
n //= 10 # drop the last digit
print("Digit sum:", digit_sum)
print("Reversed:", reversed_n)| n | digit | digit_sum | reversed_n |
|---|---|---|---|
| 4096 | 6 | 6 | 6 |
| 409 | 9 | 15 | 69 |
| 40 | 0 | 15 | 690 |
| 4 | 4 | 19 | 6904 |
Your turn: sum of 1 to n
Change the number in the Input box and run it again:
n = int(input("Add up 1 to which number? "))
total = 0
for i in range(1, n + 1):
total += i
print(f"1 + 2 + ... + {n} = {total}")
print("Formula check:", n * (n + 1) // 2)