Module 2: Control Flow and Reliable Text

Readable Decisions and Loops

Readable Decisions and Loops

Control flow lets a program choose, repeat, search, and stop. Python for loops consume iterables, while while loops repeat until a changing condition becomes false.

Module: Module 2: Control Flow and Reliable Text

Core mental model

This lesson is built around four connected ideas. Read them as a decision framework, then prove each one with the walkthrough.

  • if, elif, and else should make mutually exclusive rules obvious.
  • for fits a known stream of items; while fits state-driven repetition.
  • break exits, continue skips one iteration, and pass is only a placeholder.
  • Loop else runs after normal exhaustion but not after break.

Walkthrough

target = "ERROR"
lines = ["INFO ready", "WARN retry", "ERROR timeout"]

for line_number, line in enumerate(lines, start=1):
    if not line.strip():
        continue
    if line.startswith(target):
        print(f"found at line {line_number}")
        break
else:
    print("target not found")

enumerate supplies the position without manual indexing. The loop else expresses the not-found path without a flag, because it runs only when the search exhausts its input.

Hands-on lab

Create a three-attempt access-code loop. Blank input should not consume an attempt, a correct code should stop immediately, and while else should report lockout.

What to watch for

  • A while condition that never changes creates an infinite loop.
  • Deep nesting is usually a signal to extract named functions.
  • Loop else also runs for an empty iterable because no break occurred.

Engineering checklist

  • Connect the lesson's mental model to the choices made in the walkthrough.
  • Test the normal case, an empty or boundary case, and one invalid case.
  • Keep external input, side effects, and reusable logic in clearly separated layers.
  • Prefer the clearest correct implementation before optimizing or generalizing it.

Completion check

You can implement the lab without copying the example, explain the core concepts in your own words, and show tests or terminal output that demonstrate the expected and failure paths.