25
Advanced Loops
Advanced Loops: Controlling When to Exit and When to Fall Back
What You Might Be Wondering
"I can write loops already. Why is there an advanced lesson?"
Because most loop bugs aren't about "can you loop" — they're about exit timing and fallback logic.
One-Line Definition
Advanced loops are about fine-grained flow control: for...else, nested loops, and search patterns.
Real-Life Analogy
Looking for a book:
- Found it? Stop searching.
- Searched everywhere and didn't find it? Then show "not found."
That's for...else.
Minimal Working Example (for...else)
nums = [1, 3, 5, 7]
target = 4
for n in nums:
if n == target:
print("Found")
break
else:
print("Not found")
Nested Loops
for row in range(1, 4):
for col in range(1, 4):
print(f"({row},{col})", end=" ")
print()
Search Pattern (Worth Memorizing)
found = False
for item in items:
if condition_met:
found = True
break
if not found:
print("No match")
Quick Quiz (5 min)
- Use
for...elseto search for a username. - Print a 9x9 multiplication table.
- Search a 2D list for a target value and output its coordinates.
Quiz Rubric & Grading Criteria
- Direction: write runnable code that covers the core requirements and edge cases from the prompt.
- Criterion 1 (Correctness): main flow produces correct results, key branches execute.
- Criterion 2 (Readability): clear variable names, no excessive nesting.
- Criterion 3 (Robustness): basic protection against empty values, type errors, or unexpected input.
Take-Home Task
Build an "inventory lookup":
- Input: a 2D product table
- Find the target SKU, output its position, and stop
- If not found, output a message
Acceptance Criteria
You can independently:
- Explain when
for...else'selseblock actually runs - Write maintainable nested loops
- Use the search-match-exit pattern
Common Errors & Debugging Steps (Beginner Edition)
- Error message looks like gibberish: read the last line for the error type (
TypeError,NameError, etc.), then trace back to the offending line. - Not sure what a variable holds: drop a temporary
print(variable, type(variable))to check. - Changed code but nothing happened: make sure you saved the file, you're running the right file, and your terminal environment (venv) is correct.
Common Misconceptions
-
Misconception:
for...else'selseruns every time. -
Reality: it only runs if the loop completes without hitting a
break. -
Misconception: deeply nested loops are fine if they work.
-
Reality: past two levels, extract the inner logic into a function.