While Loops, break, and continue
A while loop repeats as long as a condition stays true. Use it when you do not know in advance how many times you will loop, like waiting for a correct guess. You will also learn break and continue, the two ways to steer any loop.
What You'll Learn
- The while loop and why the condition must eventually become false
breakto exit a loop earlycontinueto skip to the next iteration- Choosing between
forandwhile
The while Loop
The most important line is count += 1. Without something that moves the condition toward false, the loop would run forever. Always make sure your condition will eventually stop.
break: Exit Early
break immediately stops the loop. It is perfect for "keep going until you find it":
continue: Skip One
continue skips the rest of the current iteration and jumps to the next:
while True with break
A common pattern is an intentional forever-loop that you exit with break once a condition is met:
This is exactly the shape of the number guessing game: keep asking until the guess is right, then break.
for vs while
- Use for when you know the items or the count in advance
- Use while when you loop until some condition changes
Key Takeaways
while condition:repeats while the condition is true- Always change something so the loop can end
breakexits the loop;continueskips to the next iterationwhile True:plusbreakloops until a condition is metforfor known counts,whilefor unknown counts

