Python Basics — While Loop
While Loop
A while loop repeats as long as a condition is True. Unlike for loops that iterate over a known sequence, while loops are for situations where you don’t know in advance how many iterations you’ll need.
Basic Syntax
while condition:
# code to repeat
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
How it works:
- Check condition (
count <= 5) - If
True, run the body - Go back to step 1
- If
False, exit the loop
Infinite Loops (and How to Avoid Them)
If the condition never becomes False, the loop runs forever:
# WARNING: Infinite loop! (Don't run this)
# while True:
# print("This never stops!")
Common causes:
- Forgetting to update the loop variable
- Condition that can never become False
- Logic errors
# Bug: forgot to increment count
count = 1
# while count <= 5:
# print(count)
# # Missing: count += 1 → infinite loop!
Intentional infinite loop with break:
while True:
user_input = input("Type 'quit' to exit: ")
if user_input == "quit":
print("Goodbye!")
break
print(f"You typed: {user_input}")
Counter-Controlled While Loops
When you know how many times to repeat but need more control:
# Countdown
countdown = 5
while countdown > 0:
print(f"{countdown}...")
countdown -= 1
print("Liftoff!")
Output:
5...
4...
3...
2...
1...
Liftoff!
while-else
Like for-else, the else block runs when the condition becomes False (not via break):
attempts = 0
password = "secret"
while attempts < 3:
guess = input("Enter password: ")
if guess == password:
print("Access granted!")
break
attempts += 1
print(f"Wrong! {3 - attempts} attempts remaining.")
else:
print("Account locked! Too many failed attempts.")
If all 3 attempts fail, else runs. If the correct password is entered, break skips the else.
Input Validation Pattern
One of the most common uses of while:
while True:
try:
age = int(input("Enter your age: "))
if age < 0 or age > 150:
print("Please enter a realistic age.")
continue
break
except ValueError:
print("Invalid input. Please enter a number.")
print(f"Your age: {age}")
Menu-Driven Program
while True:
print("\n--- Menu ---")
print("1. Say Hello")
print("2. Say Goodbye")
print("3. Exit")
choice = input("Choose (1-3): ")
if choice == "1":
print("Hello, World!")
elif choice == "2":
print("Goodbye, World!")
elif choice == "3":
print("Exiting...")
break
else:
print("Invalid choice. Try again.")
for vs while
| Feature | for | while |
|---|---|---|
| Use when | Iterating over a sequence | Repeating until a condition changes |
| Iterations | Known in advance | Unknown / dynamic |
| Common use | Processing items | Input validation, game loops |
| Risk | Rarely infinite | Can be infinite |
| Typical | for item in list: |
while condition: |
Rule of thumb: If you’re iterating over something, use for. If you’re waiting for something, use while.
Practical Examples
Sum Until Negative
total = 0
while True:
num = float(input("Enter a number (negative to stop): "))
if num < 0:
break
total += num
print(f"Total: {total}")
Finding a Number
import random
target = random.randint(1, 100)
guesses = 0
while True:
guess = int(input("Guess (1-100): "))
guesses += 1
if guess < target:
print("Too low!")
elif guess > target:
print("Too high!")
else:
print(f"Correct! You got it in {guesses} guesses.")
break
Summary
while condition:repeats as long as the condition isTrue- Always ensure the condition will eventually become
False - Use
breakfor controlled exit from intentional infinite loops while-elseruns the else block when the condition becomesFalse- Use
while True+breakfor input validation patterns - Prefer
forwhen iterating over sequences; usewhilewhen waiting for a condition
Next up: break, continue, pass →