Lesson · Control Flow
Loop Control
45 min readLoop Control
Loop control changes the normal flow of repetition. `break`, `continue`, and loop `else` are small features that can make search and validation code clearer when used deliberately.
Learning goals
- Trace the search loop and say which values are skipped, tested, and never visited.
- State the exact rule for a loop
else: it runs when the loop ends withoutbreak. - Use
passandcontinuecorrectly and explain what each does to the rest of the loop body. - Replace a flag variable with
breakplus loopelse, and judge which version reports "not found" more clearly. - Restructure a nested search so one exit leaves both loops, given that Python has no labeled
break.
Mental model
The three statements act at different points: continue restarts the cycle early, break exits the loop immediately, and pass does nothing at all except satisfy the grammar. The loop else is not tied to the last pass: it runs exactly when the loop ends without a break, which is why it pairs naturally with search code.
Mental model
read it top to bottom
in each pass: hit continue → abandon this pass, ask for the next item hit break → abandon the whole loop, skip the loop else loop ends by exhaustion → the loop else runs
Core idea
Loop control is about exit paths. continue abandons one pass, break abandons the loop, and the loop else runs only on the quiet path where the iterable was exhausted without a break. Once you ask which exit each input takes, a search reads directly: the else means "no early exit happened", and a break placed next to the success condition documents where the search stopped.
break
break ends the innermost enclosing loop immediately: no further items are requested and the loop's else block is skipped. Control resumes at the first statement after the loop.
continue
continue ends only the current pass: the rest of the loop body is skipped and the loop asks for its next item, or re-tests its condition in a while loop.
pass
pass is a no-op statement used where the grammar requires a statement but no action is wanted, such as an empty body or a branch to fill in later. It performs nothing and does not change control flow.
Loop else
A loop else block runs when the loop finishes normally and does not run when break exits the loop. It is particularly useful for search logic.
Early exits
An early return, break, or raised exception can reduce indentation by handling exceptional or completed paths immediately. Overuse can still make control flow fragmented, so optimize for readability.
Nested-loop control strategies
When inner-loop break is insufficient, extract a function, return a result, use a flag deliberately, or restructure the search. Python has no labeled break.
Walkthrough
values = [3, 8, 12, 17, 21]is the search space andtarget = 17is the value to find; each pass begins withif value < 10: continue, so 3 and 8 jump straight to the next iteration without ever reaching the equality test.- 12 passes the guard and fails
value == target; the body simply ends, which advances the loop just as quietly, so the only pass that reachesprintis the one wherevalueis 17. - At 17 the loop prints
found 17and hitsbreak, so 21 is never visited and the loop'selseblock is skipped; had every value failed the test, the iterator would have been exhausted andprint("not found")would run instead. - Predict before running: the single line this script prints, and what the script would print if the
breakwere deleted. (Both messages appear in that second version, because the loop then ends without an early exit.)
Experiments to try
- Delete the
breakand run again. The output gainsnot foundbecause the loop now finishes normally, so restore the line and contrast the two exit paths. - Set
target = 8and predict the output before running: the value is in the list but below thecontinuethreshold, so the equality test never sees it and the loop reportsnot found. - Replace the
continuewith anif value >= 10:wrapper around the remaining body, then compare readability: the wrapper shifts the search code right, whilecontinuekeeps the main path at one indentation level. - Swap
breakforpassand explain the new output:passcompletes the pass as a no-op, so every value is still tested and the loopelsefires even after a match.
Common mistakes
- Reading the loop
elseas the counterpart ofif/else: it runs whenever the loop ends withoutbreak, even when the loop ran zero times, so it means "completed normally", not "something was true". - Placing
continuebefore the test that matters: values skipped early never reach the later checks, so a match hidden below the jump silently reportsnot found. - Using
passwherecontinuewas meant:passis a completed no-op statement, so the rest of the body still runs, whilecontinuewould skip it. - Expecting
breakinside nested loops to leave both loops: it exits only the innermost one, so the search continues in the outer loop until a function return or an explicit flag stops it.
Practice: Easy
- Trace the worked example by hand with
values = [3, 8, 12, 17, 21]andtarget = 17: list which values reach the equality test and which are cut off bycontinue. Run the script and check the single printed line against your trace. - Set
target = 8and predict the output before running. Explain why a list that contains the target still printsnot found. - In the REPL, run
for i in range(3): passfollowed byprint("done"). Replacepasswithcontinueand confirm the output does not change, then explain what each statement actually did.
Practice: Medium
- Rewrite the search without a loop
elseusing afound = Falseflag that flips on a match and checked after the loop. Compare the two versions: which one makes the not-found path clearer, and which has more moving parts? - Rewrite the search as
def find(values, target):returning the found value orNone. Explain how a singlereturnreplaces bothbreakand the loopelse. - Search a list of lists (for example
[[1, 2], [3, 17], [4]]) with nested loops, show thatbreakstops only the inner loop, then rewrite it with a helper function so onereturnleaves both loops.
Practice: Hard
- Implement
find_in_matrix(matrix, target)that returns a(row, col)tuple orNone, using a helper function andreturninstead of flags. Test with a target in the first row, a target in the last row, and a target that is absent. - Build a failure lab with three entries: a search whose
breakis removed so the loopelsefires after a match, acontinuethat hides a valid match, and a nestedbreakthat leaves the outer loop running. Record the output of each and cite the exit rule that produces it. - Rewrite the search with
any(value == target for value in values)and compare what is gained and lost:anyshort-circuits on the firstTrue, but it returns a Boolean and never tells you which value matched.
Lesson checklist
- I can trace the search loop and name which values are skipped, tested, and left unvisited.
- I can state the loop
elserule exactly: it runs only when the loop ends withoutbreak. - I can choose between
passandcontinueand say what each does to the rest of the body. - I can restructure a nested search so a single exit leaves both loops.
Remember
`break` and `continue` add two exits to a loop's normal one: `continue` abandons the current pass for the next item, and `break` abandons the loop entirely, which also suppresses the `else` block. That `else` is mechanical rather than intuitive: it runs whenever the loop ends without a `break`, so search code reads it as "no early exit happened". Keep each jump next to the condition that justifies it, and reach for a function return when one `break` cannot leave two loops.
Interview angles
What is the main purpose of **break**?+
break exits the innermost enclosing loop immediately: no later passes run and the loop's else block is skipped. In a search, it is the statement that stops the scan the moment the answer is found.
What should you pay attention to when using **continue**?+
continue abandons only the current pass and returns control to the loop header for the next item. Statements below it are skipped for that item, but later iterations proceed normally, so anything placed after a continue only runs for values that do not trigger it.
How does **pass** fit into this lesson?+
pass is a no-op statement that fills a slot the grammar requires, such as an empty body or a branch to complete later. It performs no operation and changes no control flow, so inside a loop it behaves like any other completed statement.
Why can a `continue` placed too early hide a valid match?+
Values that hit continue never reach the tests below it, so a match that those tests would find is never observed. The loop then ends without break and the else block reports not found even though the value was present.