← Back to Blog

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 if block inside the loop must be indented — 4 more spaces from the loop body
  • The loop always runs through everything — if decides what happens with each item
  • in checks 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 + if is the most common pattern in Python
  • The loop visits every item — the if filters and reacts
  • You can combine a counter with for + if to track specific items
  • Indentation stacks — the if block is indented inside the loop block
[ login to bookmark ] // copied! 21 views · 1 min
// resources
Code Example for_if_pattern.py
← prev This One's Yours — FOR next → pass — the silent keeper
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.