Python Control Flow: Conditionals, Loops, and Comprehensions
I practiced Python control flow across conditionals, loops, and the structural match statement, then refactored nested loops into comprehensions. Comprehension-based code was both more readable and measurably faster than the equivalent explicit loops.
Objective & Context
Control flow is where most logic bugs live. This lab builds idiomatic patterns – early returns, comprehension filtering, and match for dispatch – that keep automation code flat and testable instead of deeply nested.
Environment & Prerequisites
- Python 3.11 (for structural pattern matching).
- An activated venv and a script file.
timeitfor micro-benchmarks.
flowchart LR
In[Input] --> M{match value}
M -->|case A| A[Handler A]
M -->|case B| B[Handler B]
M -->|_| D[Default]
Step-by-Step Execution
1. Filter with a comprehension
python -c "print([n*n for n in range(10) if n%2==0])"2. Dispatch with match
def route(cmd):
match cmd:
case "start": return start()
case "stop": return stop()
case _: return usage()
3. Benchmark loop vs comprehension
python -m timeit "[x for x in range(1000)]"[0, 4, 16, 36, 64]
20000 loops, best of 5: 18.2 usec per loop
Validation & Testing
Compare outputs and timing of the explicit-loop and comprehension versions of the same task. Pass criteria: identical results, comprehension is faster, and the match dispatcher covers every case including the default.
Advanced: Troubleshooting
- Off-by-one: remember
rangeis half-open; the stop value is excluded. - Unreachable case: order
matchcases from specific to general. - Comprehension too complex: if it needs comments, use an explicit loop.
Key Results
- Refactored nested loops into comprehensions with measurable speedup.
- Implemented a
matchdispatcher covering 100% of cases plus default. - Flattened logic using early returns to cut nesting depth.
- Benchmarked patterns with timeit rather than guessing.