Ravindra BagaleCourses & study guides मराठी Track your progress

Python for Loops and while Loops Explained with Examples (range, break, continue)

P6.6 break and continue in Python Loops

Why. Sometimes you want to stop early (found what you need) or skip bad items (empty rows).

What. break stops the whole loop. continue skips to the next item.

How.

Control a loop

  1. Add an if inside the loop.
  2. Use break to stop.
  3. Use continue to skip this item.

Worked example A — Stop at the first problem.

Step 1 — What we do. We look for the first negative balance in a list.

Step 2 — Type and run this code.

balances = [500, 230, -40, 900]
for b in balances:
    if b < 0:
        print("First negative:", b)
        break

Step 3 — Output you should see.

First negative: -40

Step 4 — What it means. After finding -40 the loop stops. 900 is never checked.

Worked example B — Skip empty values.

Step 1 — What we do. Some patient temperature readings are missing (None).

Step 2 — Type and run this code.

temps = [98.6, None, 99.1, None, 100.4]
total = 0
count = 0
for t in temps:
    if t is None:
        continue
    total += t
    count += 1
print(round(total / count, 2))

Step 3 — Output you should see.

99.37

Step 4 — What it means. Missing readings are skipped, so the average uses only 3 real values. pandas does this skip automatically for NaN.

Ravindra Bagale's Tip

break exits only the innermost loop. Keep loops shallow — two levels deep is usually the limit for readable code.