PY-01-007-P · Primer — for & while Loops
The idea in one sentence
A loop is how you tell Python to do the same work more than once — a for loop walks through a collection of things one at a time, a while loop keeps going as long as a condition stays true, and break, continue, and else let you steer that repetition instead of just riding it.
Why it exists
Almost nothing useful happens exactly once: you total a shopping cart item by item, you retry a network call until it succeeds, you print every row in a report, you keep asking for a password while it's wrong. Without loops you'd have to copy-paste the same lines for every item — impossible when you don't know how many items there are until the program runs. Loops exist so you can write the work once and let Python repeat it for you, however many times the data or the situation demands. Python splits this into two shapes because there are two different questions: "do this for each of these things" (a for loop, when you have a collection) and "do this while something is still true" (a while loop, when you have a condition but not a fixed count). Getting comfortable with both — and with how to jump out early or skip an item — is the difference between describing a task and actually automating it.
How it works
A for loop names a variable and pulls values out of any iterable (a list, a string, a range) one at a time, running its indented body once per value. When you just need to count, range(n) hands you 0, 1, … n-1 without you building a list yourself. A while loop instead checks a condition before every pass; as long as that condition is true it runs the body again, so something inside the loop must eventually make the condition false or it runs forever. You'll usually reach for for when you know the collection and while when you're waiting for a state to change. Here are all three ideas — for over a list, for over range, and a while with a condition — in one runnable block:
total = 0
for n in [4, 8, 15, 16]: # walk the list, one value at a time
total = total + n
print(total) # 43
for i in range(3): # range(3) -> 0, 1, 2
print("tick", i) # tick 0 / tick 1 / tick 2
password = ""
attempts = 0
while password != "open" and attempts < 3: # keep trying WHILE wrong
attempts = attempts + 1
password = "open" if attempts == 2 else "nope"
print("unlocked in", attempts, "tries") # unlocked in 2 tries
Notice the while loop guarantees it will stop: attempts climbs every pass, so even if the password never became "open" the attempts < 3 half of the condition eventually goes false. Inside a loop you also have break (leave the loop entirely, right now) and continue (skip the rest of this pass and jump to the next one) to control the flow.
The one gotcha
Python loops have an else clause, and it means the opposite of what almost everyone guesses. A loop's else block does not run "if the loop was empty" — it runs when the loop finished naturally, i.e. only if break never fired. Think of it as "and we got through the whole thing without bailing out." That makes for/else and while/else perfect for search-style code: loop looking for something, break the instant you find it, and put the "not found" handling in else.
numbers = [4, 9, 15, 22]
for n in numbers:
if n % 2 == 0:
print("found an even:", n) # found an even: 4
break
else:
print("all odd") # (skipped — the break ran)
Because a break happened, the else is skipped; delete the break (or give it a list with no even numbers) and the else runs. The related trap is the infinite loop: a while whose condition never becomes false — usually because you forgot to change the variable it checks. If a program hangs and does nothing, an infinite loop is the first suspect; press Ctrl+C to stop it, then make sure every path through the body moves the condition toward false.
See it — how one pass through a loop decides what to do next
flowchart TD
A["Start loop"] --> B{"More items, or<br/>condition still true?"}
B -->|"No"| C{"Did a break<br/>ever fire?"}
C -->|"No"| D["Run the<br/>else block"]
C -->|"Yes"| E["Skip else,<br/>loop is done"]
B -->|"Yes"| F["Run the loop body"]
F --> G{"Hit break or<br/>continue?"}
G -->|"break"| E
G -->|"continue"| B
G -->|"neither"| H["Finish this pass"]
H --> B
The one-line takeaway
Use for to repeat over a collection and while to repeat while a condition holds; break bails out, continue skips one pass, else runs only when no break fired, and every while must make its condition eventually false.
Where you'll meet it
You'll write a for loop within your first hour of real Python — summing a list, printing each line of a file, checking every item in a cart — and range() will be your go-to whenever you want to repeat something a fixed number of times or generate index positions. while shows up the moment you're waiting on something instead of counting: retry a request until it succeeds, keep prompting a user until the input is valid, run a game loop until the player quits. break and continue become second nature in filtering and searching ("stop at the first match," "skip the blank rows"), and the for/else pattern is the clean, Pythonic way to say "I searched the whole list and found nothing." The infinite-loop gotcha will bite you at least once — a program that just hangs — and recognizing it instantly, Ctrl+C-ing out, and spotting the variable you forgot to update is a rite of passage every programmer earns. From data processing to web servers to tiny scripts, loops are the engine underneath nearly everything you'll build.
Named concepts: for over iterables and range, while with a condition, break and continue, loop else and infinite loops
