Choosing with if
P41.repeating-and-choosing.02 · Audience: guest, language-pro, it-ml · Prerequisites: Doing something to every item — a loop
A loop does the same thing to every item. But real tasks have a decision in the
middle: keep the long words, skip the short ones; flag the terms that need a
gloss, leave the rest. On paper you glance at each word and decide. if is that
glance — a yes-or-no test inside the loop that chooses which items to act on.
ⓘ Concept: if runs its body only when the test is true
if len(word) > 5: asks a yes-or-no question about the item — "is this word longer than five letters?" — using the comparison you met in P40. When the answer is True, the indented lines under the if run; when it is False, Python skips them and moves on.Why it matters — A decision is what turns 'do this to everything' into 'do this to the ones that matter' — the difference between a blunt tool and a useful one.
Ask the mentor about this module
Ask a question about this content. The mentor explains and grounds its answer in what you are studying; asking is recorded as a learning signal, not a grade.
🎓 Practice ladder
1 graded rung · ~5 minYour turn: loop over a list of words, keep only the ones longer than five letters into a new list, and count them — the long-word tally, automated. Press Run.
Explorer rung — keep only the long words
Loading exercise…
Where next?
Go up a level