← Back to Blog

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!

  • if can go at any level — outer, inner, or both
  • break inside 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

  • if inside a loop filters what happens with each item
  • In nested loops — filter at the outer level, inner level, or both
  • break stops the current loop only — not the one above it
  • Two levels of nesting is usually enough — beyond that, readability suffers
[ login to bookmark ] // copied! 21 views · 2 min
// resources
Code Example for_if_nested.py
← prev When one loop isn't enough next → while sets the pace — for does the work
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.