Chapter 3: Strings and Loops / Lesson 18

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:

while.py
count = 0 while count < 5: print(count) count += 1 # Important: increment to avoid infinite loop # Output: 0, 1, 2, 3, 4

Loop Control: break and continue

You can control loop execution with break (exit loop) and continue (skip to next iteration):

control.py
count = 0 while count < 10: count += 1 if count == 3: continue # Skip iteration when count is 3 if count == 7: break # Exit loop when count is 7 print(count) # Output: 1, 2, 4, 5, 6

Infinite Loops

An infinite loop runs forever (or until manually stopped). Use them carefully with break to exit:

infinite.py
# Pattern for user input validation while True: user_input = input("Enter 'quit' to exit: ") if user_input.lower() == "quit": break print(f"You entered: {user_input}") print("Goodbye!")

While Loop with Condition

Common patterns for while loops include counting, checking status, and processing until a condition is met:

patterns.py
# Countdown timer = 5 while timer > 0: print(f"Time remaining: {timer}") timer -= 1 print("Time's up!") # Process until condition is met number = 10 while number % 2 == 0: print(f"{number} is even") number += 1 print(f"{number} is odd")

Nested While Loops

You can nest while loops inside other while loops for complex patterns:

nested.py
# Print multiplication table i = 1 while i <= 3: j = 1 while j <= 3: print(f"{i} × {j} = {i * j}", end=" ") j += 1 print() # New line i += 1

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).

🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...