CodeMIRAI
0 XP

Loop patterns: sums, counting down and more

4 min read 14 runnable examples Quiz included

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:

Python
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:

IterationiWhat runs
11prints "Iteration number 1"
22prints "Iteration number 2"
33prints "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:

Python
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 loop

total = total + i is usually written total += i. The first few iterations:

itotal beforetotal after
101
213
336
4610
.........
104555

To watch the total grow, print inside the loop:

Python
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:

Python
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:

Python
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:

Python
for i in range(10, 0, -1):
    print(i, end=" ")
print()          # finish the line

The same countdown with while:

Python
n = 10
while n >= 1:
    print(n)
    n -= 1       # without this, n stays 10 and the loop never ends

Sums with a condition: even and odd numbers

i % 2 == 0 is true for even numbers (dividing by 2 leaves no remainder):

Python
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:

Python
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.

Python
n = 5
fact = 1
for i in range(1, n + 1):
    fact *= i
print(f"{n}! = {fact}")

Times tables

Python
n = 7
for i in range(1, 11):
    print(f"{n} x {i} = {n * i}")

Totals over a list: sum, average and largest

Python
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:

Python
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)
ndigitdigit_sumreversed_n
4096666
40991569
40015690
44196904

Your turn: sum of 1 to n

Change the number in the Input box and run it again:

Python
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)
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.