20. Loop patterns — Homework solutions

The .py solution files are in exercises/20/homework/solutions/.

Problem 1 — Factorial

Problem. Multiply 1 through 5 together.

How to think about it. Accumulate, but with * instead of +. Start the product at 1 — start at 0 and the answer is 0, since anything times zero is zero.

Worked solution.

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

Problem 2 — Count multiples

Problem. Count numbers from 1 to 50 that divide evenly by 7.

Worked solution.

hits = 0
for i in range(1, 51):
    if i % 7 == 0:
        hits = hits + 1
print(hits)        # 7   (7, 14, 21, 28, 35, 42, 49)

Problem 3 — First big square

Problem. Find the first number whose square is over 200.

Worked solution.

first = None
for i in range(1, 101):
    if i * i > 200:
        first = i
        break
print(first)       # 15   (14×14 = 196, 15×15 = 225)

Common mistakes.

  • Forgetting break, so the loop runs on and first lands on the last match, not the first.

Challenge — Range stats in one pass

Problem. Total, even-count, and a divisible-by-9 flag from one loop.

Worked solution.

total = 0
evens = 0
has_nine = False

for i in range(1, 21):
    total = total + i
    if i % 2 == 0:
        evens = evens + 1
    if i % 9 == 0:
        has_nine = True

print("total", total)              # 210
print("evens", evens)              # 10
print("divisible by 9", has_nine)  # True   (9 and 18)

Common mistakes.

  • Writing three separate loops over the same range. One pass does all three jobs — that is why you learn to spot the patterns.

Done?

That ends Part 4. You can branch with if, reason about truth with and/or/not, repeat with every kind of loop, nest loops for grids, and pick the right loop pattern on sight. Part 4 has two mini-projects to tie it together: the Number Guessing Game and Rock-Paper-Scissors.