Repeating
Worked examples
Read the claim, then run it and check the machine agrees. One at a time — nothing here is taken on trust.
prices = [100, 101, 99, 103]
total = 0
for r in prices:
total += r
print("loop :", total)
print("sum :", sum(prices))
The loop starts total at 0 and folds each price in, landing on 403.
sum(prices) is 403 too — it is this loop, wrapped up with a name. Use
sum when you just want the total; write the loop out when you need to do
something extra on each pass (like also tracking the biggest).
pnls = [12, -8, 5, -20, 3]
worst = pnls[0]
for pnl in pnls:
if pnl < worst:
worst = pnl
print("running min:", worst)
print("builtin min:", min(pnls))
Same loop shape as the total, but the fold is "keep it if it's smaller"
instead of "add it". Starting worst at the first element (pnls[0]) is a
safe identity — the worst can only go down from there. Both routes give
-20, matching min(pnls).
balance = 1000.0
for year in range(3):
balance = balance * 1.05
print("by loop :", round(balance, 3))
print("by formula:", round(1000 * 1.05 ** 3, 3))
print("raw formula:", 1000 * 1.05 ** 3)
Three passes of range(3) — years 0, 1, 2 — multiply the balance by 1.05
each time. Rounded, the loop and the closed form both read 1157.625. The
raw closed form prints 1157.6250000000002: the loop isn't "more accurate",
both live with the same float dust — which is why we compare rounded.
Check the concept
One question at a time. Unsure? Revisit the lecture, then answer.
The challenge
Pass the quiz to unlock the challenge — your code will still be waiting here.