While loops and loop control
Repeat while a condition holds, prove that a loop can finish, and use break and continue carefully.
By the end, you’ll be able to…
- Trace the condition, body, and state update of a while loop.
- Use break and continue without accidentally preventing progress.
- Explain when a loop else clause executes.
01Repeat while a condition remains true
A while loop checks its condition before each iteration. When the condition is true, Python runs the indented body and then checks again. When it becomes false, the loop ends. Unlike a for loop, a while loop does not automatically take the next item from a collection. Your program must make the relevant state move toward completion.
For a countdown, the state is the number remaining and the update subtracts one. Trace the first check, one full body execution, and the next check. Notice that a loop may execute zero times when its condition is false at the beginning. Prefer for when visiting a known collection; use while when repetition is naturally governed by changing state rather than a predetermined sequence of items.
02Find the progress that makes termination possible
Before running a while loop, identify what can make its condition false. A retry counter should increase; a remaining balance should decrease; a stream of work should eventually supply an ending signal. If nothing relevant changes, the loop may continue indefinitely. An iteration limit can make a simulation or retry policy explicitly bounded, but it should represent an intentional rule rather than hide an unexplained bug.
The example models repeated practice until a target is reached. The final total can overshoot the target because the condition is checked before adding the next session. That is expected here: the requirement is to reach at least 50 minutes. If the requirement were to reach exactly 50, the update rule would need a different design. A terminating loop can still implement the wrong business rule.
03Stop early or skip an iteration deliberately
break exits the nearest enclosing loop immediately. It is useful when a search has found the first suitable item or an ending marker means later values should be ignored. continue skips the rest of the current body and moves to the next iteration. In a while loop, that means returning to the condition check; in a for loop, it means requesting the next item.
A continue placed before a while loop's progress update can accidentally repeat the same state forever. Keep that update reachable on every path that continues. This deterministic example processes a fixed list as if it were a stream of readings: negative readings are ignored and zero is the stop marker. Printing the result after the loop makes the difference between skipping one item and ending the whole process visible.
04Use loop else for completion without break
Both for and while loops can have an else clause. It executes when the loop finishes normally without a break: a for loop exhausts its items, or a while condition becomes false. It can execute even when the loop body runs zero times. Read this else as 'no break occurred,' rather than associating it with the nearest condition inside the loop.
A search demonstrates the idea. If an acceptable reading appears, break suppresses the fallback message. If every item is examined without finding one, else reports that outcome. A separate found flag can express the same behavior and may feel clearer initially. Choose the version your readers can explain reliably. If a loop needs several flags, nested exits, and complicated updates, consider simplifying the task into smaller steps.
The ideas worth keeping.
- A while loop must change relevant state or reach a deliberate exit.
- break ends the nearest loop; continue skips the remainder of one iteration.
- Loop else describes completion without break, including the empty case.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Count bounded attempts
Use a while loop to print Attempt 1, Attempt 2, and Attempt 3, then print Finished. Start attempts at zero and make the update explicit.
Explore a worked solution
attempts = 0while attempts < 3: attempts += 1 print(f"Attempt {attempts}")print("Finished")Incrementing before display gives human-readable numbers 1 through 3. The counter eventually makes attempts < 3 false, so the loop terminates.
Search for the first long name
From ['Ada', 'Mira', 'Noor', 'Alexandra'], print the first name longer than five characters and stop searching. If none qualifies, print No long name. Use break and a loop else clause.
Explore a worked solution
names = ["Ada", "Mira", "Noor", "Alexandra"]for name in names: if len(name) > 5: print(name) breakelse: print("No long name")Alexandra is the first qualifying value. The break ends the search and prevents the else clause from printing its fallback. An empty list would take the fallback path.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Count bounded attempts
Use a while loop to print Attempt 1, Attempt 2, and Attempt 3, then print Finished. Start attempts at zero and make the update explicit.
Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Attempt 0 Finished
Keep exploring.
The official references behind this chapter, when you want a second angle or the full details.
One chapter closer.
Reading is a start. Trying it yourself makes the connection.