18. Loops — Homework solutions
The .py solution files are in
exercises/18/homework/solutions/.
Problem 1 — Count to 20
Problem. Print 1 through 20 with a
while loop.
How to think about it. A while loop
needs a start value, a stop condition, and an update. Start at 1, stop
past 20, add 1 each pass.
Worked solution.
i = 1
while i <= 20:
print(i)
i = i + 1Common mistakes.
- Forgetting
i = i + 1. The condition stays True forever, so the loop never ends. - Using
i < 20, then missing 20.<=includes the endpoint.
Problem 2 — Multiplication table of 7
Problem. Print 7 * i = result for
i from 1 to 12.
How to think about it. A for loop with
range(1, 13). Each pass prints a line from i
and 7 * i.
Worked solution.
for i in range(1, 13):
print(f"7 * {i} = {7 * i}")Common mistakes.
- Writing
range(1, 12). That stops at 11 and misses the last line.range(start, stop)excludesstop, so userange(1, 13)to reach 12. - Confusing
7 * i(printed) withi(the counter).
Problem 3 — Stop at the threshold
Problem. Add 1, 2, 3, ... to a total. Stop once it exceeds 100. Print the counter and the total.
How to think about it. Two variables: a counter that
grows by 1 each pass, and a total that grows by the counter. The exit,
total > 100, fits inside as if ... break,
which suits while True:.
Worked solution.
i = 1
total = 0
while True:
total = total + i
if total > 100:
break
i = i + 1
print("Stopped at i =", i, "with total =", total)For i = 1..14, the sum 1+2+...+14 = 105 is
the first total over 100:
Stopped at i = 14 with total = 105
Common mistakes.
- Adding
i = i + 1before adding tototal. That adds the nexti, not the current. Order them on purpose. - Putting the
breakafteri = i + 1. Then the printediis one past the value that pushed the total over 100. Either works; be deliberate.
Challenge — Sum 1..N
Problem. Read n, sum 1..n with a
for loop, compare with the closed form
n * (n + 1) // 2.
How to think about it. A for loop from
range(1, n + 1) adds each counter to a total. The closed
form for the first n positive integers is
n * (n + 1) // 2, Gauss's trick. Print both, confirm they
match.
Worked solution.
n = int(input("Enter a positive whole number n: "))
total = 0
for i in range(1, n + 1):
total = total + i
print(f"Sum from 1 to {n} is {total}")
print("Formula gives", n * (n + 1) // 2)// is integer division, so both lines show whole
numbers. Expected.
Common mistakes.
- Writing
range(1, n). That stops atn - 1and gives the wrong answer. Userange(1, n + 1)to includen. - Forgetting to set
totalto0before the loop. - Writing the formula as
n * n + 1 // 2. Order of operations matters: the parentheses around(n + 1)are needed.
Done?
You can now repeat work with every kind of loop. Next, Nested loops nests loops to build grids, and Loop patterns names the jobs loops do most. Then Part 4's mini-projects — a Number Guessing Game and Rock-Paper-Scissors — combine decisions and repetition.