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!
whilecontrols how long —forcontrols what happens insidebreakinsideforstops thefor— not thewhile- Update the
whilecondition 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 sequencesbreakinsideforstops only thefor—whilekeeps going- The
forloop runs completely on everywhileiteration - Combine with
random,input(), and counters for real programs