A loop repeats instructions while a condition holds or for each value supplied by an iterable.
Follow changing state through for and while loops, and understand how break and continue affect execution.
A running total must remember what earlier iterations contributed. Start with three prices and track that state after each round; then compare a loop driven by items with one driven by a stopping condition. The key checks are what stays true after a round and what eventually ends the repetition.

Total a canteen bill
A canteen till has a list of prices for one order: chai ₹40, samosa ₹15,
vada pav ₹60. A for loop visits each one, and a running total collects
them. Step through it and watch total climb:
price is assigned the next value each round: 40, then 15, then 60. The body is
the indented block under the for, and indentation is the only thing that
says where it ends. Get it wrong and the loop quits after one item:
This should print 115. It prints 40. Fix the indentation.
Refunds show up as negative prices, and the till should skip them.
continue ends this round early and moves to the next item:
Preparing this topic’s interactive investigation…
What is true after each iteration?
After processing k prices in the first loop, total equals the sum of
exactly those k prices. This is an invariant: a fact the loop preserves.
Before any items, k = 0 and the sum is 0. Each round adds just the next
item. At the end, the same fact describes the whole bill.
| Prices processed | total |
|---|---|
| none | 0 |
| 40 | 40 |
| 40, 15 | 55 |
| 40, 15, 60 | 115 |
Resetting total = 0 inside the loop breaks this fact: you remember only
the current price. Returning inside it breaks completion: you stop after
the first prefix. Empty input tests initialization and return placement
because the body never runs.
The refund-skipping version has a different invariant: sum of the nonnegative prices processed so far. Writing that sentence first helps you decide whether skipping refunds is the intended rule. A net-sales report would normally include negative adjustments.
Retry a UPI PIN
A payment app gives you three tries at your PIN. You don't know how many
rounds you need (the right PIN may come first), so this is a job for
while: keep going while tries are left, and break out on success.
Forget tries += 1 and tries < 3 stays true forever: an infinite
loop. The page will stop it after a few seconds, but a real app just
freezes. The other classic slip is where the counter starts:
tries = 1
while tries < 3:
print(tries, end=" ")
tries += 1When the number of rounds is fixed, a for reads better. And a loop can
have an else: it runs only when the loop finished without a break.
That is exactly "all three tries failed":
Use for when an iterable supplies the next item, even if its length is
unknown. Use while when a condition determines whether to continue.
The PIN demonstration supplies exactly three inputs; a shorter list would
need a separate exhaustion check.
Find a free seat
A cinema hall is three rows of seats, X for taken and . for free. To
look at every seat you need a loop inside a loop: the outer one picks a
row, the inner one walks that row's seats. range(len(...)) gives the
positions, so we can print a seat name like B2:
We want only the first free seat. Run it and see two. Why does it keep going?
Each outer iteration starts a new inner scan. Without an early exit, three
rows of three seats require nine checks; the inner break can stop a row
early. A 20-row hall with 30 seats per row permits up to 600 checks. Count
the actual work before assuming every nested loop performs the full product.
One-liners you'll use daily
Looping over a string gives its characters, and looping over a dictionary gives its keys.
Trap:
passis notcontinue.passmeans "do nothing here" and carries on to the next line of the same round. It fills a spot where Python needs a statement but you have nothing to write yet.
For while, identify what moves toward termination. Here 3 - tries
decreases every attempt, including failures. A continue before the
increment could prevent progress. break exits only the nearest loop.
A loop's else also runs for empty input, because no break occurred.
Build a longest-success-streak counter for [True, True, False, True].
It needs a current streak and a best-so-far value; only the current streak
resets on failure. Explain both after the third item, then test empty input,
all failures and a longest streak at the end. This uses two processed-prefix
facts instead of one.
Quick practice
for i in range(2, 10, 3):
print(i, end=" ")total = 0
for p in [50, -20, 30]:
if p < 0:
pass
total += p
print(total)for code in ["SAVE10", "STUDENT"]:
if code == "HALF":
print("found it")
break
else:
print("no HALF code")A T20 innings has overs 1 to 20. This list is one short. Fix it.
🎯 Your turn
Write sum_items(prices). It adds up a list of prices with a loop and returns
the total:
sum_items([10, 20, 5.5])→35.5sum_items([])→0
Hint: start total = 0, then for price in prices: total += price, and
return total after the loop.
Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below goes from doubling a list to a full sales summary.
Practice — level up
0/5 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write double_all(nums) returning a new list with every number doubled, using a list comprehension.
Write running_totals(nums) returning the list of running sums — [10, 20, 5] → [10, 30, 35].
Write invoice_lines(names, prices, qtys) — three parallel lists — returning strings like "soup x2 = $20.00" (price × qty, 2 decimals). Use zip.
Write pair_sums(nums, target) returning every pair [a, b] (earlier index first, no repeats) whose values add to target, in order.
Write sales_summary(days, sales) (parallel lists) returning a dict {"total", "best_day", "average"} — total sales, the day with the highest sales, and the mean rounded to 2 decimals. Empty input → {"total": 0, "best_day": None, "average": 0}.