Skip to the workspace
Pebellslearn by building
Fundamentals  ›  Lesson

Loops

Loops 20 minA loop repeats instructions while a condition holds or for each value supplied by an iterable.

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.

Before the loop total is 0; then three rounds each take one price, 40, 15 and 60, and total grows 0 to 40, 40 to 55, 55 to 115; print(total) sits after the loop and runs once, while a print indented inside would fire in round 1

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:

step through it
1prices = [40, 15, 60]
2total = 0
3for price in prices:
4 total += price
5print(total)

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:

broken — fix it

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:

python

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.

python

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:

What does this print?
tries = 1
while tries < 3:
    print(tries, end=" ")
    tries += 1

When 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":

python

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:

broken — fix it

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

python

Looping over a string gives its characters, and looping over a dictionary gives its keys.

Trap: pass is not continue. pass means "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

What does this print?
for i in range(2, 10, 3):
    print(i, end=" ")
What does this print?
total = 0
for p in [50, -20, 30]:
    if p < 0:
        pass
    total += p
print(total)
What does this print?
for code in ["SAVE10", "STUDENT"]:
    if code == "HALF":
        print("found it")
        break
else:
    print("no HALF code")
broken — fix it

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.5
  • sum_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.

Your task
Build sum_items(prices). It adds up a list of prices with a loop and returns the total. Example: sum_items([10, 20, 5.5]) → 35.5.

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upDouble every number

Write double_all(nums) returning a new list with every number doubled, using a list comprehension.

comprehension
DrillRunning totals

Write running_totals(nums) returning the list of running sums — [10, 20, 5] → [10, 30, 35].

loopsaccumulator
BuildInvoice lines

Write invoice_lines(names, prices, qtys) — three parallel lists — returning strings like "soup x2 = $20.00" (price × qty, 2 decimals). Use zip.

zipcomprehensionf-strings
BossPair sums

Write pair_sums(nums, target) returning every pair [a, b] (earlier index first, no repeats) whose values add to target, in order.

nested-loopscomprehensionconditionals
CapstoneSales summary

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}.

zip/indexsum/maxdictf-strings
Project context and further resources
You're building a piece ofBill Splitter & Tip Calculator
This piece — sum_items(): Adds up the individual food items on the check.
Scenario The table ordered soup ($10), steak ($20) and a shared dessert ($5.50). The app totals the items before tip.
sum_items.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
sum_items(prices) → floatAdd up every price in the list.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.