← Back to Blog

while sets the pace — for does the work

The problem...

You need a loop that runs an unknown number of times. And inside each iteration — you need to process a sequence completely.

One loop can't do both. while handles the outer condition. for handles the inner sequence.

The idea!

while sets the pace — it decides how long the whole thing runs. for does the work — it processes every item in the sequence on each iteration.

The syntax

while condition:
    for item in sequence:
        # runs for every item, every while iteration

Your first while + for

import random

attempts = 0

while attempts < 3:
    word = random.choice("bull horn red".split())
    print(f"\nWord: {word}")
    for letter in word:
        print(f"  {letter}")
    attempts += 1
# Word: horn
#   h
#   o
#   r
#   n
# Word: bull
#   b
#   u
#   l
#   l
# Word: red
#   r
#   e
#   d

while runs 3 times. Each time — random picks a word — for loops through every letter. Three rounds. Three words. All letters printed.

A real example — input and process

while True:
    word = input("Enter a word (or 'quit'): ")
    if word == "quit":
        break
    count = 0
    for letter in word:
        if letter.lower() in "aeiou":
            count += 1
    print(f"Vowels in '{word}': {count}")

The while True keeps asking. For every word — the for counts vowels. The user decides when to stop.

break and continue in while + for

while True:
    word = input("Enter a word (or 'quit'): ")
    if word == "quit":
        break               # stops the while loop
    for letter in word:
        if letter == "x":
            print("Found x — skipping rest of word.")
            break           # stops the for loop only
        print(letter)

The outer break stops the while. The inner break stops the for. Each break only affects its own loop.

Heads up!

  • while controls how long — for controls what happens inside
  • break inside for stops the for — not the while
  • Update the while condition inside the loop — or it runs forever
  • Each level adds 4 spaces of indentation

The mindset shift

Stop thinking: "I need one loop for everything."

Start thinking: "while sets the pace. for does the work. Each has its job."

What you should understand now

  • while + for — outer controls duration, inner processes sequences
  • break inside for stops only the forwhile keeps going
  • The for loop runs completely on every while iteration
  • Combine with random, input(), and counters for real programs
[ login to bookmark ] // copied! 21 views · 2 min
// resources
Code Example while_for_nested.py
← prev Loop and decide — together next → Nested Loops Mini Project — Caesar Cipher
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.