for. Searching or waiting? reach for while.
for loop counts. A while loop waits for something to happen — and stops the moment it does.
while loop — condition firstbreak — leave early · continue — skip aheadfor vs while — choosing the right toolwhile loop checks a condition, then repeats.Read it as a sentence: "while this is still true, keep doing the body." Before every pass, Python re-checks the condition.
count = 3
while count > 0: # condition — checked before each pass
print(count)
count = count - 1 # move toward making the condition False
print("done")
# → 3, 2, 1, done
You don't always know how many passes you'll need. With while you don't have to — you loop until a goal is met.
# first number >= start divisible by 7
n = 50
while n % 7 != 0: # keep going until we find one
n = n + 1
print(n) # → 56
break — jump out of the loop now
break stops the loop immediately, ignoring whatever the condition says. Perfect for "I found it — I'm done."
n = 50
while True: # "loop forever" — break is the only exit
if n % 7 == 0:
break # found a match — leave right away
n = n + 1 # otherwise try the next candidate
print(n) # → 56
while True: + a check + break is the classic find-first-match.
continue — skip the rest of this pass
continue jumps straight back to the condition check, skipping the rest of the body — but the loop keeps going.
# print only the odd numbers 1..6
n = 0
while n < 6:
n = n + 1
if n % 2 == 0:
continue # even → skip the print
print(n)
# → 1, 3, 5
break = leave the loop entirely.continue = skip to the next pass.
# BUG: count never changes
count = 3
while count > 0:
print(count)
# condition stays True forever
# → 3, 3, 3, 3, ... ∞
# FIX: update the condition variable
count = 3
while count > 0:
print(count)
count = count - 1 # moves toward False
# → 3, 2, 1 ✓
while body must change something that the condition depends on — otherwise it runs forever. (Stuck? Press Ctrl + C to stop it.)
for vs whileUse when you know the count up front — "do this 10 times", "for each item in the list".
Use when you don't know the count — "until the user quits", "until we find a match".
for. Searching or waiting? reach for while.
Condition, body, and the all-important update — every idea from today, in five lines.
def countdown(n):
while n >= 1: # condition
print(n) # body
n = n - 1 # update — or it loops forever!
print("Liftoff!")
countdown(3) # → 3, 2, 1, Liftoff!
> 0 when you meant >= 1, or stopping one step too early/late.continue, so the update gets skipped and the loop hangs.while when a simple for over a known range would be clearer.
Use a while loop to print n, n-1, … 1, then "Liftoff!". Remember the update.
Return the first integer >= start divisible by n, found with while + break.
students/<your-username>/D08_find_first_match.py. Full brief in lab/module_1_foundations/D08_find_first_match/problem.md. PR before 12:00.
while loop that runs until a condition is met.
break and continue to control a loop precisely.