for meets if — the most common pattern in Python
The problem...
Your loop processes every item the same way. Every time. Without exception.
But real programs don't work like that. Sometimes you need to act on some items and ignore others. Check a condition. React differently based on what you find.
The idea!
You already know for. You already know if. Put them together — and you have the most common pattern in Python.
The syntax
for item in sequence:
if condition:
# runs only for items where condition is True
The loop moves through every item. The if decides what happens with each one.
Your first for + if
word = "RedHorn"
for letter in word:
if letter == "o":
print("Found it!")
# Found it!
The loop checks every character. Only when it finds "o" — it acts.
for + if + else
word = "Bull"
for letter in word:
if letter == "u":
print(f"{letter} — vowel")
else:
print(f"{letter} — consonant")
# B — consonant
# u — vowel
# l — consonant
# l — consonant
Every item gets checked. Every item gets a response. The loop and the decision work together.
Using a counter with for + if
word = "RedHorn"
count = 0
for letter in word:
if letter.lower() in "aeiou":
count += 1
print(f"Vowels found: {count}")
# Vowels found: 2
The loop moves through every character. The if catches only vowels. The counter tracks them. Three tools — one pattern.
Heads up!
- The
ifblock inside the loop must be indented — 4 more spaces from the loop body - The loop always runs through everything —
ifdecides what happens with each item inchecks if a value exists in a sequence —letter in "aeiou"is True if letter is a vowel
The mindset shift
Stop thinking: "The loop handles everything the same way."
Start thinking: "The loop visits everything. The if decides what to do with each visit."
What you should understand now
for+ifis the most common pattern in Python- The loop visits every item — the
iffilters and reacts - You can combine a counter with
for+ifto track specific items - Indentation stacks — the
ifblock is indented inside the loop block