Python If Else
Make decisions with if, and repeat work with for and while.
Why it matters: Training loops are for-loops. Filters use if. Early stop uses break.
Basics
If / Elif / Else
if runs a block when a condition is True.
elif tries another condition. else runs when none matched.
Indent with four spaces.
Empty values like 0, "", and None are falsy. For scores, compare explicitly: if score >= 0.7:
Common mistake: using if score: and treating 0.0 as missing.
Tiny example
One condition. Two paths.
score = 0.82
if score >= 0.7:
print("keep")
else:
print("drop")Basics
For and While
for item in sequence: is the default loop.
Use range(n) for integers. Use enumerate() when you need an index.
break leaves the loop. continue skips to the next item.
while repeats until a condition fails.
Common mistake: an infinite while loop.
Tiny example
Loop over each item.
labels = ["pos", "neg", "pos"]
for label in labels:
print(label)Then AI / ML
AI / ML examples
Same idea, used in real AI work. Press Try in lab to run it.
AI / ML example
AI / ML: filter by score
Keep high scores. Drop the rest.
In AI / ML: Classifiers often keep only predictions above a threshold.
example.py
Python
preds = [0.92, 0.41, 0.77]
kept = []
for score in preds:
if score >= 0.7:
kept.append(score)
print(kept)AI / ML example 2
AI / ML: early stop idea
Stop when loss stops improving.
In AI / ML: Training scripts watch validation loss and stop early.
example.py
Python
losses = [0.9, 0.7, 0.61, 0.66]
best = losses[0]
for loss in losses:
if loss < best:
best = loss
print(best)Takeaways
- 1if / elif / else branch on conditions.
- 2for-loops walk lists and ranges.
- 3break stops a loop early.