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)Your turn · answer checked automatically
Exercise
Loop over scores. Append scores of 0.8 or more to high, scores from 0.5 up to (not including) 0.8 to medium, and the rest to low. Use for, if, elif and else.
Edit the code, then press Run & check. Passing it marks this lesson done.
python console
Exercise
~/lesson.py
Ctrl+Enter
console output
ready
$ waiting for Run...Takeaways
- 1if / elif / else branch on conditions.
- 2for-loops walk lists and ranges.
- 3break stops a loop early.