Flow controls: Loops · 4 / 26 Theory

Counters and accumulators

Almost every useful loop keeps something while it runs. There are three patterns you will see again and again.

Counter: how many times something happens

counter = 0
for i in range(1, 21):
    if i % 3 == 0:
        counter += 1
print(counter)   # 6 multiples of 3 between 1 and 20

Sum accumulator

total = 0
for i in range(1, 6):
    total += i
print(total)   # 15

Product accumulator

You start at 1, not 0 (with 0 everything would be 0):

product = 1
for i in range(1, 6):
    product *= i
print(product)   # 120 (the factorial of 5)

Maximum and minimum

largest = int(input())
for _ in range(2):
    n = int(input())
    if n > largest:
        largest = n
print(largest)

You start from the first value read; this way it also works with negative numbers (starting at 0 would give a wrong result if all of them are negative).

Dividing until exhausted: digits and factors

With while and integer division you can "consume" a number:

n = 4721
digits = 0
while n > 0:
    n = n // 10
    digits += 1
print(digits)   # 4
n = 360
factor = 2
while n > 1:
    if n % factor == 0:
        print(factor)   # 2 2 2 3 3 5
        n = n // factor
    else:
        factor += 1

Returning change

An accumulator that keeps subtracting: with // and % you know how many coins of each kind fit and what remainder is left:

change = 87
for coin in [50, 20, 10, 5, 2, 1]:
    amount = change // coin
    change = change % coin
    print(coin, amount)

Practice with Product of a number, Return change, Product of prime factors and Multiples numbers.