Loop patterns

Part of the free LogicWiz Python course, Module 2: Decisions and loops. The examples and practice run in the app.

Kabir's practical file needs the sum 1 + 1/2 + 1/3 + … + 1/10, and the canteen wants the day's biggest bill. Both are the same three-step trick.

You'll learn to

  • Keep a running sum, a count and a maximum
  • Add up a series term by term
  • Leave a loop early with break, skip a round with continue
  • Use the loop else to say "never found it"

Learn

The accumulator pattern

Almost every "total / count / biggest" program has three steps:

  1. Before the loop: start the result (total = 0, count = 0).
  2. Inside the loop: update it with each value (total += x).
  3. After the loop: use it (print(total)).

The start value matters: 0 for a sum, 1 for a product, and the first value for a maximum or minimum.

A running sum

total = 0
for n in range(1, 6):
    total += n
print(total)

Step through and watch total: 1, 3, 6, 10, 15. The print is not indented, so it runs once, after the loop.

Count and maximum from input

best = int(input())
passed = 1 if best >= 50 else 0
for i in range(4):
    score = int(input())
    if score >= 50:
        passed += 1
    if score > best:
        best = score
print("Highest:", best)
print("Scored 50+:", passed)

Five scores. The first one starts best, then each new score that beats it replaces it. 1 if best >= 50 else 0 is a one-line if: 1 when the first score passed, otherwise 0.

Series sums

n = 5
total = 0
for i in range(1, n + 1):
    total += 1 / i
print(round(total, 4))

x = 2
s = 0
for i in range(n):
    s += (-1) ** i * x ** i
print(s)

First: 1 + 1/2 + 1/3 + 1/4 + 1/5. Second: 1 - x + x² - x³ + x⁴, where (-1) ** i flips the sign every term. The trick: write the i-th term as a formula, then add it up in a loop.

CBSE Class 11 practicals list series like 1 + x + x² + … + xⁿ, 1 - x + x² - … and x + x²/2 + x³/3 + …. Write the general term (for the last one, x ** i / i), choose the range, then accumulate. Show the trace table for full marks.

break and continue

for n in range(1, 11):
    if n % 3 == 0:
        continue
    if n > 8:
        break
    print(n, end=" ")
print()
print("after the loop")

continue skips the rest of this round and goes to the next one (no 3 or 6). break leaves the loop completely (stops at 9 before printing it).

Loop else: "I never broke out"

n = 29
for d in range(2, n):
    if n % d == 0:
        print(n, "is divisible by", d)
        break
else:
    print(n, "is prime")

The else of a loop runs only if the loop finished without break. Here no divisor was found, so it runs. Change n to 21 and run it again.

Two classic slips. Putting total = 0 inside the loop resets it every round, so you get only the last value. And the loop else must line up with for, not with the if inside it.

In one line

Start the result before the loop, update it inside, use it after; continue skips a round, break leaves, loop else runs only if there was no break.