Loop and decide — together
The problem...
You've seen for alone. You've seen if alone. You've even seen them together — briefly.
But in nested loops, the combination becomes essential. You're not just looping and deciding. You're looping, looping again, and deciding at every level.
The idea!
if inside a for loop filters what happens with each item. In a nested loop — you can filter at the outer level, the inner level, or both.
if in the outer loop
word = "RedHorn"
vowels = "aeiou"
for letter in word:
if letter.lower() in vowels:
print(f"{letter} — vowel")
# e — vowel
# o — vowel
The outer loop visits every letter. The if filters — only vowels get printed.
if in the inner loop
words = "red horn bull".split()
target = "o"
for word in words:
for letter in word:
if letter == target:
print(f"Found '{target}' in '{word}'")
# Found 'o' in 'horn'
Outer loop moves through words. Inner loop moves through letters. if catches the match.
if at both levels
words = "red horn bull".split()
vowels = "aeiou"
for word in words:
if len(word) > 3:
for letter in word:
if letter in vowels:
print(f"{word} — vowel found: {letter}")
# horn — vowel found: o
Outer if filters by word length. Inner if filters by vowel. Only words longer than 3 characters are checked — and only their vowels are printed.
break inside a nested loop
words = "red horn bull".split()
target = "o"
for word in words:
for letter in word:
if letter == target:
print(f"Found '{target}' in '{word}'")
break # stops the inner loop only
break inside a nested loop stops the inner loop — not the outer one. The outer loop keeps going.
Heads up!
ifcan go at any level — outer, inner, or bothbreakinside a nested loop stops the inner loop only- Each level of nesting adds 4 spaces — keep track of your indentation
- Deeply nested code gets hard to read — two levels is usually the limit
The mindset shift
Stop thinking: "I loop first, then I decide."
Start thinking: "I loop and decide at the same time — at every level."
What you should understand now
ifinside a loop filters what happens with each item- In nested loops — filter at the outer level, inner level, or both
breakstops the current loop only — not the one above it- Two levels of nesting is usually enough — beyond that, readability suffers