Rana Maninder Singh
Lesson 7 of 9Python basics

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:

  1. Loop for cid in ... over a column and print each value.
  2. Use range when you need positions, not values.
  3. Accumulate a running total with +=.
  4. break at the first Platinum customer.
  5. continue to skip a row that fails a test.
  6. 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
C0005

Step 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 C0003

Step 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:

10

Step 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":
        break

Expected output:

C0001
C0002

Step 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
C0004

Step 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:

62

A 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 -= 1

Expected output:

2
1

If 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. break leaves the loop immediately. Later rows are not visited.

Q2. What is the difference between break and continue?

break stops the whole loop. continue skips 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)
        break

Expected output:

C0005

Independent 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:

92

Common mistake

The deliberate mistake

Symptom: the script hangs, or gold prints 300.

Diagnosis: a while with no count -= 1, or an if that never fails so every row increments.

Correction: for over the column; increment only when segment == "Gold"; break only 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 with continue.
  • 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.