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
- Add an if inside the loop.
- Use
breakto stop. - Use
continueto 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.
Ravindra Bagale's Tip – मराठी
break फक्त सर्वात आतला loop थांबवतो. Loops उथळ ठेवा — वाचनीय code साठी दोन पातळ्या पुरेशा.
Ravindra Bagale's Tip – हिंदी
break सिर्फ़ सबसे अंदर का loop रोकता है. Loops कम गहरे रखो — पढ़ने लायक code के लिए दो levels काफ़ी.