🕯️ Magic Note
The while loop is the original loop in programming. Early languages had only while and goto. for loops are actually a convenient abstraction built on top of while. Understanding while means understanding the foundation of all iteration.
Python
# Simple counter
count = 1
while count <= 5:
print(count)
count += 1
# Output:
# 1
# 2
# 3
# 4
# 5
Python
# INFINITE LOOP (dangerous!)
# while True:
# print(“This never stops”)
# Common mistake: forgetting to update the variable
x = 0
# while x < 10:
# print(x)
# # x never changes! Infinite loop!
# Correct way
x = 0
while x < 10:
print(x)
x += 1 # Update condition variable
| Use for When... | Use while When... |
|---|---|
| Iterating over a list, tuple, string, or range | Condition depends on runtime values |
| Number of iterations is known (or bounded) | Number of iterations is unknown in advance |
| You need to transform each element of a sequence | Reading from a file until EOF |
| You want to loop a fixed number of times | User input validation (keep asking until valid) |
| You want the most readable, Pythonic option | You need infinite loops (game loops, servers) |
Python
# For loop: known sequence
for fruit in [“apple”, “banana”, “cherry”]:
print(fruit)
# While loop: unknown number of iterations
user_input = “”
while user_input != “quit”:
user_input = input(“Enter ‘quit’ to exit: “)
print(f”You entered: {user_input}”)
Python
# Keep asking until user enters a positive number
num = -1
while num < 0:
num = int(input(“Enter a positive number: “))
if num < 0:
print(“That is not positive. Try again.”)
print(f”Thanks! You entered {num}”)
# With error handling
while True:
try:
age = int(input(“Enter your age: “))
if 0 <= age <= 120:
break
print(“Please enter a valid age (0-120)”)
except ValueError:
print(“That is not a number. Try again.”)
print(f”Age: {age}”)
🕯️ Magic Note
The pattern while True with a break inside is very common. It means “loop forever, but break when a condition is met”. This is often cleaner than checking a condition at the top, especially when the exit condition is in the middle of the loop.
Python
# Countdown
count = 10
while count > 0:
print(count)
count -= 1
print(“Blast off!”)
# Output:
# 10
# 9
# …
# 1
# Blast off!
Python
# While loop style (old school)
with open(“data.txt”, “r”) as f:
line = f.readline()
while line:
print(line.strip())
line = f.readline()
# Better: for loop (Pythonic)
with open(“data.txt”, “r”) as f:
for line in f:
print(line.strip())
Python
# break: exit the loop
num = 1
while num <= 100:
if num * num > 50:
break
print(f”{num}^2 = {num**2}”)
num += 1
# continue: skip to next iteration
num = 0
while num < 10:
num += 1
if num % 2 == 0:
continue
print(num, end=” “)
# 1 3 5 7 9
Python
# Search a list until found
items = [1, 3, 5, 7, 9]
target = 4
i = 0
while i < len(items):
if items[i] == target:
print(f”Found {target} at index {i}”)
break
i += 1
else:
print(f”{target} not found”)
# Output: 4 not found
Python
# Using a flag variable
is_running = True
attempts = 0
while is_running and attempts < 3:
password = input(“Enter password: “)
if password == “magic”:
print(“Access granted”)
is_running = False
else:
attempts += 1
print(f”Wrong. {3 – attempts} attempts left”)
if attempts == 3:
print(“Access denied”)
Python
# Multiplication table (1 to 5)
i = 1
while i <= 5:
j = 1
while j <= 5:
print(f”{i} x {j} = {i * j}”, end=” “)
j += 1
print()
i += 1
Python
# For loop
for i in range(5):
print(i)
# Equivalent while loop
i = 0
while i < 5:
print(i)
i += 1
🕯️ Magic Note
A for loop is essentially a while loop with a built-in iterator. The for loop automatically fetches the next item and handles the StopIteration exception. This is why for is preferred: it is safer and less error-prone.
Python
# Simple menu system
choice = 0
while choice != 3:
print(“\n=== Main Menu ===”)
print(“1. Say Hello”)
print(“2. Show Date”)
print(“3. Exit”)
choice = int(input(“Select option: “))
if choice == 1:
print(“Hello, dear user!”)
elif choice == 2:
from datetime import date
print(f”Today is {date.today()}”)
elif choice == 3:
print(“Goodbye!”)
else:
print(“Invalid option. Try again.”)
- Forgetting to update the condition variable (infinite loop)
- Using == instead of = when updating variables
- Off-by-one errors (check your comparison operators: < vs <=)
- Using while for simple iteration when for would be cleaner
- Confusing break (exits loop) with continue (skips iteration)
- Putting a semicolon after the condition (like C/C++): while x < 10;
- Not handling the case where the loop should run zero times
- Write a while loop that prints numbers from 1 to 10.
- What is an infinite loop and how do you avoid it?
- Write a input validation loop that keeps asking until the user enters “yes” or “no”.
- What is the difference between break and continue?
- When should you use while instead of for?
- What does the else clause do in a while loop?
⚡ Whisper
The while loop is patient. It asks a question, then waits. If the answer is Yes, it takes one step. Then it asks again. And again. It does not know how many steps it will take. It only knows the question. Is the user done? Is the file empty? Is the number still small? These are the questions that guide the while loop. It is the loop of uncertainty. The loop of waiting. The loop of “I will continue until something changes.” Master the while loop, and you master situations where the end is not known in advance. You learn to trust the condition, not a fixed count. You learn to be patient. You learn to ask. Again. And again. Until the answer changes.