while Loops
Keep repeating as long as a condition is True — perfect when you do not know in advance how many times to loop.
"A for loop says 'do this for each item'. A while loop says 'keep doing this until I tell you to stop'."
— ShurAIfor vs while — Which One?
Examples:
• Print each item in a list
• Repeat exactly 10 times
• Process each student
Examples:
• Keep asking until correct answer
• Run game until player quits
• Read until end of file
Basic Syntax
A while loop checks a condition before every iteration. As long as the condition is True, the loop keeps running:
Example 1 — Countdown Timer ⏱️
count = 5
while count > 0:
print(f"{count}...")
count = count - 1 # must decrease count or it loops forever!
print("🚀 Blast off!")
5...
4...
3...
2...
1...
🚀 Blast off!
If you forget to change the variable inside the loop, the condition never becomes False and your program runs forever. Always ask: "What changes each time to eventually make the condition False?" To stop an infinite loop: press Ctrl + C in the terminal.
Example 2 — Number Guessing Game 🎯
The while loop is perfect here — we don't know how many guesses the player needs:
secret = 42
guessed = False
tries = 0
print("🎯 Guess the number (1-100)!")
while not guessed:
guess = int(input("Your guess: "))
tries += 1
if guess < secret:
print("📈 Too low! Try higher.")
elif guess > secret:
print("📉 Too high! Try lower.")
else:
guessed = True # this stops the loop!
print(f"🎉 Correct! You got it in {tries} tries.")
🎯 Guess the number (1-100)!
Your guess: 50
📉 Too high! Try lower.
Your guess: 25
📈 Too low! Try higher.
Your guess: 42
🎉 Correct! You got it in 3 tries.
Example 3 — Keep Asking Until Valid Input ✅
One of the most practical uses of while loops — don't let the program continue until the user gives a valid answer:
# Keep asking until user enters a number between 1 and 10
number = 0
while number < 1 or number > 10:
number = int(input("Enter a number between 1 and 10: "))
if number < 1 or number > 10:
print("❌ Out of range. Try again.")
print(f"✅ You chose: {number}")
Example 4 — Interactive Menu 📋
A classic pattern — keep the program running until the user chooses to exit:
running = True
while running:
print("\n=== 🍕 Pizza Menu ===")
print("1. Order pizza")
print("2. Check my order")
print("3. Exit")
choice = input("Choose (1/2/3): ")
if choice == "1":
print("🍕 Pizza ordered! 30 minutes delivery.")
elif choice == "2":
print("📦 Your order is being prepared!")
elif choice == "3":
print("👋 Thank you! Goodbye.")
running = False # stops the loop
else:
print("⚠️ Invalid choice.")
The while True Pattern
while True creates an intentional infinite loop that you exit with break. Very common in menus and games:
# while True — loops forever until break is hit
while True:
answer = input("Type 'quit' to stop: ")
if answer.lower() == "quit":
print("Bye!")
break # exit the loop immediately
print(f"You typed: {answer}")
If you can write it with a for loop, use a for loop. Use while when the number of repeats depends on what happens during the loop — user input, game state, reading data, or any condition that changes unpredictably.
"The while loop is patient. It will keep going, check after check, until the world is exactly as it should be."
— ShurAI🧠 Quiz — Question 1
When should you use a while loop instead of a for loop?
🧠 Quiz — Question 2
What happens if you never change the loop variable inside a while loop?
🧠 Quiz — Question 3
In the number guessing game, what makes the while loop stop?
🧠 Quiz — Question 4
What does while True: create, and how do you exit it?