PART 1 · PYTHON FROM ZERO · LESSON 9
Loops part 2: while, break, continue
FreeLesson 11 of 78
A while loop repeats as long as a condition stays True. break and continue control any loop from the inside.
balance = 1000
day = 0
while balance > 0: # keep going while this is True
day += 1
balance -= 300
print(f"day {day}: balance {balance}")
print("ran out on day", day)Output
day 1: balance 700 day 2: balance 400 day 3: balance 100 day 4: balance -200 ran out on day 4
statuses = ["delivered", "", "cancelled",
"delivered", "STOP", "delivered"]
delivered = 0
for s in statuses:
if s == "":
continue # skip this one, go to the next
if s == "STOP":
break # leave the loop completely
if s == "delivered":
delivered += 1
print("delivered before STOP:", delivered)Output
delivered before STOP: 2
attempt = 0
connected = False
while not connected and attempt < 3:
attempt += 1
connected = attempt == 3 # pretend the 3rd try works
result = "connected" if connected else "failed"
print(f"try {attempt}: {result}")
if not connected:
print("giving up")Output
try 1: failed try 2: failed try 3: connected
This is the skeleton of every retry in data engineering: a counter, a limit, and a flag that ends the loop early. Page 37 turns it into a reusable decorator.
| Use for when | Use while when |
|---|---|
| You know what you are looping over: a list, a file, range(10) | You loop until something happens: money runs out, a retry succeeds |
| Most of the time in data work | Waiting, polling, retrying, reading an API page by page |
amounts = [796, 1198, 2397, 1499, 3498]
found_at = None
for i, a in enumerate(amounts):
if a > 2000:
found_at = i
break # stop at the first match
print("first above 2,000:", amounts[found_at], "at", found_at)Output
first above 2,000: 2397 at 2
Set a "not found yet" value (None) before the loop, then break when you find what you want. Without break the loop keeps going and wastes time on a big list.
Try it yourself before moving on
- Start at 1 and keep doubling until you pass 1,000. How many doublings?
- Sum a list but stop at the first negative number.
- Sum a list of text amounts, skipping the empty ones with continue.
Watch the free lesson
The same topic in the Free Lessons library, free with a sign-in.