Control flow: if, for, while
Decisions and loops — training steps, early stopping, filtering predictions, and walking documents.
Why this matters in AI / ML / GenAI
A training loop is a for-loop over epochs and batches. RAG pipelines filter chunks with if. Eval scripts loop examples and branch on pass/fail. This is the control surface of every ML job.
if / elif / else
Conditions use the comparisons you already know. Indent the block. elif is “else if”.
Truthy / falsy: empty string, 0, [], {}, and None are falsy. A non-empty list is truthy. That is handy (if chunks:) and dangerous (if score: is false for 0.0, which may be a valid score). For numbers, compare explicitly: if score is not None:.
Compound conditions: and, or, not. Parentheses help readers.
for and while
for item in sequence: is the default loop. enumerate(seq, start=1) when you need an index. range(n) when you need integers.
break leaves the loop. continue skips to the next item. Early stopping is break when validation loss stops improving.
while is for “until a condition”. Avoid while True unless you also have a clear break — infinite loops freeze the browser compiler (it will time out after 20 seconds).
Copy-paste examples
Copy into your own editor, or load one into the compiler below and press Run.
Filter predictions by confidence
Same idea as dropping low-confidence classifier outputs before they reach users.
preds = [
{"label": "positive", "score": 0.92},
{"label": "negative", "score": 0.41},
{"label": "positive", "score": 0.77},
]
kept = []
for p in preds:
if p["score"] >= 0.7:
kept.append(p)
else:
print("drop", p)
print("kept:", kept)Mini training loop with early stop
Toy numbers — the control flow is what production trainers use.
val_losses = [0.90, 0.70, 0.61, 0.62, 0.66]
best = float("inf")
patience = 1
bad_epochs = 0
for epoch, loss in enumerate(val_losses, start=1):
print(f"epoch {epoch} val_loss={loss}")
if loss < best:
best = loss
bad_epochs = 0
else:
bad_epochs += 1
if bad_epochs > patience:
print("early stop at epoch", epoch)
break
print("best:", best)range and enumerate
range(n) is 0..n-1. That matches computer-science indexing, not human page numbers.
docs = ["intro", "method", "results"]
for i in range(len(docs)):
print(i, docs[i])
print("---")
for i, name in enumerate(docs, start=1):
print(i, name)Keep chunks under a character budget
Try it — in-browser Python
This is a simplified context-window packer. Raise the budget and see more chunks kept.
Output
Python runs in your browser. First run downloads the runtime.
Press Run (or Ctrl+Enter) to execute.
CPython in WebAssembly. Stdlib works. NumPy and pandas load on demand. No input(), no GPU, no network installs.
Takeaways
- if/elif/else branch on explicit comparisons — be careful with falsy 0 and empty lists.
- for-loops walk batches, epochs, documents, and eval rows.
- break implements early stopping; the compiler kills infinite loops after 20s.