While Loops
While Loops
While loops allow you to execute a block of code repeatedly as long as a condition is true. They're perfect for situations where you don't know in advance how many times you need to loop.
Unlike for loops, while loops continue until a condition becomes false, making them ideal for user input validation, game loops, and processing data until a certain condition is met.
Basic While Loop
The simplest while loop executes code while a condition is true. Make sure the condition eventually becomes false, or you'll create an infinite loop:
Loop Control: break and continue
You can control loop execution with break (exit loop) and continue (skip to next iteration):
Infinite Loops
An infinite loop runs forever (or until manually stopped). Use them carefully with break to exit:
While Loop with Condition
Common patterns for while loops include counting, checking status, and processing until a condition is met:
Nested While Loops
You can nest while loops inside other while loops for complex patterns:
While vs For Loops
💡 Use While Loops When:
• You don't know how many iterations you need
• You need to loop until a condition changes
• You're waiting for user input or external events
💡 Use For Loops When:
• You know how many times to iterate
• You're iterating over a collection (list, string, etc.)
• You have a specific range to cover
Common Pitfalls
⚠️ Infinite Loops
Always ensure your condition will eventually become false. If your loop variable doesn't change, you'll have an infinite loop that never stops!
⚠️ Off-by-One Errors
Be careful with your loop conditions. while count < 5 runs 5 times (0-4), but while count <= 5 runs 6 times (0-5).