Ch 5 — Control Flow
Ch 5 — Control Flow
A RAM manager that can only run straight-line code is useless. Aryan needs it to react: alert when usage crosses 90%, skip dead processes, keep polling until the user interrupts, and optionally break early if a critical threshold is hit. That reactive behavior is all control flow.
if / elif / else
The fundamental decision structure. Python evaluates each condition top-to-bottom and runs the first matching block.
used_pct = 87.3
if used_pct >= 95:
print("CRITICAL — kill something NOW")
elif used_pct >= 80:
print("WARNING — RAM running high")
elif used_pct >= 60:
print("INFO — moderate usage")
else:
print("OK — plenty of RAM free")Only one branch executes — once a condition matches, the rest are skipped.
Nested Conditionals
Conditions can nest as deep as needed (though deep nesting is a smell — prefer early returns or functions).
if used_pct > 80:
if swap_enabled:
print("High RAM but swap is cushioning it")
else:
print("High RAM with NO swap — danger zone")Ternary Expression
One-line conditional assignment.
status = "WARN" if used_pct > 80 else "OK"
color = "red" if used_pct > 90 else "yellow" if used_pct > 70 else "green"Keep ternaries short. If the logic needs more than two levels, use a full if/elif/else.
for Loop
Iterate over any iterable — list, range, string, dict keys, etc.
processes = ["chrome", "electron", "python", "kernel_task"]
for proc in processes:
print(f"Checking RAM for: {proc}")for with range
for tick in range(10): # 0 … 9
poll_ram()
for tick in range(0, 60, 5): # 0, 5, 10 … 55
print(f"Tick {tick}s")while Loop
Repeat while a condition is true — perfect for the main polling loop.
import time
running = True
while running:
snapshot = read_ram()
display(snapshot)
time.sleep(1)break
Exit the loop immediately.
for proc in processes:
if proc == "kernel_task":
print("Skipping kernel — read-only")
break # stop iterating entirelycontinue
Skip the rest of the current iteration and jump to the next.
for proc in processes:
if proc.startswith("_"):
continue # skip internal/hidden processes
print(f"Scanning {proc}…")pass
A no-op placeholder. Useful during development to satisfy syntax requirements.
def alert_user():
pass # TODO: implement Slack notificationNested Loops
Iterate a 2D dataset — e.g., multiple snapshots across multiple processes.
snapshots = [
["chrome", "electron"],
["python", "java"],
]
for snapshot in snapshots:
for proc in snapshot:
print(f" proc: {proc}")Watch out for O(n²) performance with large process lists.
Control Flow Decision Map
flowchart TD
A[Start polling loop] --> B[Read RAM snapshot]
B --> C{used_pct > 95?}
C -->|Yes| D[CRITICAL alert]
C -->|No| E{used_pct > 80?}
D --> F[break — exit loop]
E -->|Yes| G[WARNING log]
E -->|No| H[OK log]
G --> I[sleep 1s]
H --> I
I --> BLoop Control Keywords
flowchart LR
A[for / while loop] --> B{condition met?}
B -->|Yes| C[Run loop body]
C --> D{break?}
D -->|Yes| E[Exit loop immediately]
D -->|No| F{continue?}
F -->|Yes| G[Jump to next iteration]
F -->|No| H[Finish iteration body]
H --> B
B -->|No| I[Loop exhausted → else block if present]Practical Example: The Polling Loop
import time
threshold = 90.0
max_ticks = 60
for tick in range(max_ticks):
used_pct = get_ram_percent() # hypothetical function
if used_pct >= threshold:
print(f"Tick {tick}: CRITICAL at {used_pct:.1f}%")
break
elif used_pct >= 70:
print(f"Tick {tick}: WARNING at {used_pct:.1f}%")
else:
print(f"Tick {tick}: OK at {used_pct:.1f}%")
time.sleep(1)
else:
# loop completed without break
print("60-second scan complete — no critical events")The for-else (covered more in Chapter 6) runs the else block only when the loop was not interrupted by break.
Key Takeaways
if / elif / elseevaluates top-down; only the first matching branch runs.- The ternary expression (
x if cond else y) compresses simple conditionals to one line. foriterates over any iterable;range()generates sequences of integers.whilekeeps running while its condition isTrue— essential for the main polling loop.breakexits the current loop;continueskips to the next iteration.passis a syntactic no-op — use it as a placeholder during incremental development.- Nested loops work but compound time complexity; restructure or use functions to keep things readable.