Day 9 of 30Logic & Data Structures
♾️while Loops & Control
🎯 Today's objective
Repeat until a condition changes; control loops with break/continue.
📖 Key concepts
- while repeats while a condition is True
- break exits a loop
- continue skips to next iteration
- Avoid infinite loops
💻 Try this code
# 1. Countdown with while condition
countdown = 3
while countdown > 0:
print("T-minus", countdown)
countdown -= 1
print("Liftoff! 🚀")
# 2. Loop control with break
attempts = 1
while True:
if attempts > 3:
break # exit loop safely
print("attempt", attempts)
attempts += 1
# 3. Practical: Robot Battery Monitor
battery = 100
while battery > 20:
battery -= 25
print(f"Robot battery at {battery}% — status OK")
print("⚠️ Low battery (<=20%)! Returning to charging dock.")👥 Learn it your way
🧒 Young Explorers
while is "keep going until..." — like bouncing a ball until it stops.
Your task
Keep asking for a password until the user types "open" (then say "Welcome!").
💼 Professionals
Use while for unknown iteration counts; always ensure the condition can become False.
Your task
Read numbers until the user enters 0, then print the count and average.
🤖 AI connection
Many AI algorithms loop "until good enough" — repeating until error stops improving (convergence). That’s a while loop in spirit.
✅ Quick check
What does break do?
Immediately exits the loop.
Risk of a while loop?
An infinite loop if the condition never becomes False.