Course Progress21% complete
🐍 Python Basics Topic 21 / 100
⏱ 9 min read

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'."

— ShurAI

for vs while — Which One?

for loop
Use when you know the count or have a collection to go through.

Examples:
• Print each item in a list
• Repeat exactly 10 times
• Process each student
while loop
Use when you don't know the count — repeat until something happens.

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:

while condition is True :
run this code
change something so condition eventually becomes False

Example 1 — Countdown Timer ⏱️

python
count = 5

while count > 0:
    print(f"{count}...")
    count = count - 1   # must decrease count or it loops forever!

print("🚀 Blast off!")
output
5...
4...
3...
2...
1...
🚀 Blast off!
🧠 Step by step — what Python does:
Check: count (5) > 0True → print "5...", count becomes 4
Check: count (4) > 0True → print "4...", count becomes 3
Check: count (3) > 0True → print "3...", count becomes 2
Check: count (2) > 0True → print "2...", count becomes 1
Check: count (1) > 0True → print "1...", count becomes 0
Check: count (0) > 0Falseexit loop
print "🚀 Blast off!"
⚠️ The Infinite Loop Trap

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:

python
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.")
terminal
🎯 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:

python
# 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:

python
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:

python
# 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}")
for vs while — One-Line Rule

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?