Loops
Lesson opener
In one line: A for loop does the same work once per customer — print an id, add a ticket count, stop at the first Platinum — so you do not copy the same if 300 times.
Why it matters: Conditionals decided one row. The desk job is every row. A loop is that decision applied to the file. break stops early; continue skips one row; an accumulator (total += n) is a running total.
Before this lesson: Conditionals — you can band one customer. Same data/customers.csv.
Practitioner focus: The first five ids are C0001–C0005. The first Platinum is C0002. There are 62 Gold rows. Those three facts are the checks for the blocks below.
What you will learn
By the end of this lesson you will be able to:
- Loop
for cid in ...over a column and print each value. - Use
rangewhen you need positions, not values. - Accumulate a running total with
+=. breakat the first Platinum customer.continueto skip a row that fails a test.- Count Gold customers with a loop and match the 62 from Operators.
Worked example: walk the file
Step 1 — for over the first five ids. You know the collection. One indented print runs five times.
import pandas as pd
df = pd.read_csv("data/customers.csv")
for cid in df.head(5)["customer_id"]:
print(cid)Expected output:
C0001
C0002
C0003
C0004
C0005Step 2 — range when you need the row number. range(3) is 0, 1, 2 — useful for iloc.
import pandas as pd
df = pd.read_csv("data/customers.csv")
for i in range(3):
print(i, df.iloc[i]["customer_id"])Expected output:
0 C0001
1 C0002
2 C0003Step 3 — Accumulator. Same 10-ticket total as in Operators, written as the reason you loop.
import pandas as pd
df = pd.read_csv("data/customers.csv")
total = 0
for n in df.head(5)["support_tickets"]:
total += int(n)
print(total)Expected output:
10Step 4 — break at the first Platinum. C0002 is Platinum. The loop prints C0001, then C0002, then stops — it does not print C0003.
import pandas as pd
df = pd.read_csv("data/customers.csv")
for row in df.itertuples():
print(row.customer_id)
if row.segment == "Platinum":
breakExpected output:
C0001
C0002Step 5 — continue skips a row. Print ids among the first five whose tickets are greater than 1. C0002 (0 tickets) and C0003/C0005 (1 ticket) are skipped; C0001 (2) and C0004 (6) print.
import pandas as pd
df = pd.read_csv("data/customers.csv")
for row in df.head(5).itertuples():
if int(row.support_tickets) <= 1:
continue
print(row.customer_id)Expected output:
C0001
C0004Step 6 — Count Gold with a loop. This must print 62 — the same number as (df["segment"] == "Gold").sum().
import pandas as pd
df = pd.read_csv("data/customers.csv")
gold = 0
for seg in df["segment"]:
if seg == "Gold":
gold += 1
print(gold)Expected output:
62A vectorised sum is shorter. The loop is here so you can see the increment. Prefer the one-liner in production once you trust the count.
while — when you do not know the stop in advance
while repeats until a condition is false. Countdown from C0001's ticket count (2) to 1:
import pandas as pd
df = pd.read_csv("data/customers.csv")
count = int(df.iloc[0]["support_tickets"])
while count > 0:
print(count)
count -= 1Expected output:
2
1If you forget count -= 1, the loop never ends. That is the usual while bug.
Pause and think
Q1. Why did break not print C0003?
C0002 was Platinum.
breakleaves the loop immediately. Later rows are not visited.
Q2. What is the difference between break and continue?
breakstops the whole loop.continueskips the rest of this turn and goes to the next item.
Q3. When is while the wrong tool for this file?
When you already have 300 rows.
for row in df.itertuples()already knows when to stop.
Guided practice: print the first Bronze id
Walk the file and break at the first Bronze customer. That is C0005.
import pandas as pd
df = pd.read_csv("data/customers.csv")
for row in df.itertuples():
if row.segment == "Bronze":
print(row.customer_id)
breakExpected output:
C0005Independent practice: tickets on Gold rows
Deliverable: loop all 300 rows and print the total support_tickets for Gold customers only.
import pandas as pd
df = pd.read_csv("data/customers.csv")
total = 0
for row in df.itertuples():
if row.segment == "Gold":
total += int(row.support_tickets)
print(total)Expected output:
92Common mistake
The deliberate mistake
Symptom: the script hangs, or
goldprints 300.Diagnosis: a
whilewith nocount -= 1, or anifthat never fails so every row increments.Correction:
forover the column; increment only whensegment == "Gold";breakonly when you mean stop.Prevention: print the first two ids while you write the loop. If those two are wrong, do not run all 300 yet.
Where this connects
What you can now do:
- Repeat work per row.
- Stop early with
break, skip withcontinue. - Keep a running total that matches a pandas count.
Next lesson: Data structures. Loops walk a collection. Next you choose list vs dict for what you store.