While Loops - Keep Going Until...
A while loop is like washing dishes: 'WHILE there are dirty dishes in the sink, keep washing.' You don't know how many dishes there are, but you keep going until the sink is empty.
A **while loop** repeatedly executes a block of code as long as a given condition is `True`. Unlike a `for` loop, which runs a predetermined number of times (based on a sequence), a `while` loop is ideal when you don't know in advance how many iterations are needed – it continues until the condition becomes `False`.
**Basic syntax:**
```python
while condition:
# code to repeat
```
The `condition` is any expression that evaluates to `True` or `False`. As long as it is `True`, the indented block runs. When the condition becomes `False`, the loop exits and execution continues after the loop.
**The critical importance of updating the condition:**
You must ensure that something inside the loop eventually changes the condition to `False`. Otherwise, you create an **infinite loop** – the program will run forever (or until you force‑quit it).
Example of a **finite** loop (correct):
```python
count = 1
while count <= 5:
print(count)
count += 1 # updates condition
```
Example of an **infinite** loop (incorrect – will never stop):
```python
count = 1
while count <= 5:
print(count)
# forgot to increment count → condition never becomes False
```
**Using `break` to exit early:**
Sometimes you want to exit the loop immediately, regardless of the condition. Use `break`:
```python
while True: # infinite loop intentionally
response = input("Type 'quit' to exit: ")
if response == "quit":
break
print(f"You typed: {response}")
```
**Using `continue` to skip the rest of the iteration:**
`continue` jumps back to the condition check, skipping any remaining code in the current iteration:
```python
num = 0
while num < 10:
num += 1
if num % 2 == 0:
continue # skip even numbers
print(num) # prints only odd numbers
```
**`while`‑`else` clause:**
The `else` block executes **only if** the loop finishes normally (condition becomes `False`), not if the loop is terminated by `break`.
```python
n = 5
while n > 0:
print(n)
n -= 1
else:
print("Loop finished naturally.")
```
**Common use cases for while loops:**
- **Input validation** – keep asking until user enters valid data.
- **Menu‑driven programs** – show menu, perform action, repeat until user chooses exit.
- **Game loops** – run the game until player loses or quits.
- **Reading files** – read lines until end‑of‑file.
- **Number guessing games** – loop until the correct guess is made.
**Comparison with `for` loops:**
- Use `for` when you know how many times to iterate (e.g., over a list, a range).
- Use `while` when the number of iterations depends on a dynamic condition (e.g., user input, reaching a goal).
**Avoiding infinite loops (best practices):**
- Always update variables that affect the condition inside the loop.
- Use `break` with a clear exit condition.
- Consider adding a safety counter: `if iterations > 1000: break`.
- Test with small inputs first.
**Common mistakes:**
- Forgetting to update the loop variable (infinite loop).
- Using assignment `=` instead of comparison `==` in the condition.
- Off‑by‑one errors (e.g., using `>` when you need `>=`).
- Putting a semicolon after the condition (not syntax error in Python, but can cause empty body).
**Real‑world applications:**
- Validating user input (password, age, menu choice).
- Running a server that accepts connections until stopped.
- Processing data streams (until no more data).
- Implementing countdown timers.
- Simulating processes that converge to a value (e.g., Newton's method).
**Practice exercises:**
1. Write a while loop that prints numbers from 10 down to 1.
2. Keep asking the user for a number until they enter a negative number, then print the sum of all entered numbers.
3. Implement a simple calculator that repeats until user enters 'q'.
4. Write a program that repeatedly asks for a password until the correct one is entered (max 3 attempts).
5. Use a while loop to compute the factorial of a number (e.g., 5! = 120).
**Example with input validation (numeric):**
```python
while True:
try:
age = int(input("Enter your age: "))
if age > 0:
break
else:
print("Age must be positive.")
except ValueError:
print("Please enter a number.")
```
# ========== EXAMPLE 1: Basic Counting and Input Validation ==========
print("=== Example 1: Counting and Password Check ===")
# Basic counting
count = 1
while count <= 5:
print(f"Count: {count}")
count += 1
# Password validation
print("\n--- Password Checker ---")
password = ""
while password != "python123":
password = input("Enter password: ")
if password != "python123":
print("Wrong password! Try again.")
print("Access granted!")
print()
# ========== EXAMPLE 2: Number Guessing Game with Break ==========
print("=== Example 2: Number Guessing Game ===")
import random
secret_number = random.randint(1, 10)
guesses = 0
max_guesses = 3
print("I'm thinking of a number between 1 and 10.")
print(f"You have {max_guesses} guesses.")
guess = 0
while guess != secret_number and guesses < max_guesses:
guess = int(input("Your guess: "))
guesses += 1
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
if guess != secret_number and guesses < max_guesses:
print(f"Guesses remaining: {max_guesses - guesses}")
if guess == secret_number:
print(f"Congratulations! You guessed it in {guesses} tries!")
else:
print(f"Game over! The number was {secret_number}.")
print()
# ========== EXAMPLE 3: Running Total Calculator (while True with break) ==========
print("=== Example 3: Running Total Calculator ===")
total = 0
print("Enter numbers to add (enter 0 to stop):")
while True:
try:
number = float(input("Enter number: "))
if number == 0:
break
total += number
except ValueError:
print("Invalid input. Please enter a number.")
print(f"\nTotal sum: {total}")
# Bonus: using else with while
print("\n--- While-Else Demo ---")
n = 3
print("Countdown:")
while n > 0:
print(n)
n -= 1
else:
print("Blast off! Loop finished normally.")
→ Run this code interactively