Python while Loops
A while loop repeatedly executes a block of code as long as a condition remains True. Use while loops when you don't know in advance how many iterations you need.
Basic while Loop
python
count = 0
while count < 5:
print(f"Count: {count}")
count += 1
# Count: 0
# Count: 1
# Count: 2
# Count: 3
# Count: 4Warning: Always ensure the condition will eventually become False, or the loop will run forever!
while with User Input
python
# Keep asking until valid input
while True:
age = input("Enter your age: ")
if age.isdigit() and 0 < int(age) < 150:
age = int(age)
break
print("Invalid age. Please try again.")
print(f"Your age is {age}")break and continue
break - Exit the Loop Immediately
python
# Find the first even number
numbers = [1, 3, 7, 8, 5, 2]
i = 0
while i < len(numbers):
if numbers[i] % 2 == 0:
print(f"First even number: {numbers[i]}")
break
i += 1
# First even number: 8continue - Skip to Next Iteration
python
# Print odd numbers only
num = 0
while num < 10:
num += 1
if num % 2 == 0:
continue
print(num, end=" ")
# 1 3 5 7 9The else Clause
The else block runs when the while condition becomes False (not when break is used):
python
# Without break - else runs
count = 0
while count < 3:
print(count)
count += 1
else:
print("Loop completed normally")
# 0, 1, 2, Loop completed normally
# With break - else does NOT run
count = 0
while count < 10:
if count == 5:
print("Breaking at 5")
break
count += 1
else:
print("This won't print")
# Breaking at 5Infinite Loops
Sometimes you intentionally want an infinite loop:
python
# Menu-driven program
while True:
print("\n--- Menu ---")
print("1. Say Hello")
print("2. Show Date")
print("3. Exit")
choice = input("Choose option: ")
if choice == "1":
print("Hello, World!")
elif choice == "2":
from datetime import date
print(f"Today: {date.today()}")
elif choice == "3":
print("Goodbye!")
break
else:
print("Invalid choice!")while vs for
| Use Case | Preferred Loop |
|---|---|
| Known number of iterations | for |
| Iterate over a collection | for |
| Unknown number of iterations | while |
| Wait for a condition | while |
| User input validation | while |
| Game loops | while |
python
# FOR: when you know the count
for i in range(10):
print(i)
# WHILE: when you don't know the count
import random
attempts = 0
target = random.randint(1, 100)
guess = 0
while guess != target:
guess = random.randint(1, 100)
attempts += 1
print(f"Found {target} after {attempts} attempts")Common Patterns
Countdown Timer
python
import time
countdown = 5
while countdown > 0:
print(f" {countdown}...")
countdown -= 1
time.sleep(1)
print(" Go! π")Sentinel Value Pattern
python
# Process input until a sentinel value is entered
total = 0
count = 0
print("Enter numbers (type 'done' to finish):")
while True:
value = input("> ")
if value.lower() == "done":
break
try:
total += float(value)
count += 1
except ValueError:
print("Invalid number, try again")
if count > 0:
print(f"Sum: {total}, Average: {total/count:.2f}")
else:
print("No numbers entered")Two-Pointer Technique
python
# Check if a list is a palindrome
def is_palindrome(lst):
left = 0
right = len(lst) - 1
while left < right:
if lst[left] != lst[right]:
return False
left += 1
right -= 1
return True
print(is_palindrome([1, 2, 3, 2, 1])) # True
print(is_palindrome([1, 2, 3, 4, 5])) # FalseConvergence Loop
python
# Newton's method to find square root
def sqrt(n, precision=1e-10):
guess = n / 2.0
while abs(guess * guess - n) > precision:
guess = (guess + n / guess) / 2.0
return guess
print(sqrt(144)) # 12.0
print(sqrt(2)) # 1.4142135623730951Nested while Loops
python
# Print a pattern
rows = 5
i = 1
while i <= rows:
j = 1
while j <= i:
print("*", end=" ")
j += 1
print()
i += 1
# *
# * *
# * * *
# * * * *
# * * * * *Avoiding Common Mistakes
python
# Mistake 1: Forgetting to update the condition variable
# BAD - infinite loop!
# i = 0
# while i < 5:
# print(i) # i never changes!
# GOOD
i = 0
while i < 5:
print(i)
i += 1 # Don't forget this!
# Mistake 2: Off-by-one errors
# Print 1 to 5
i = 1
while i <= 5: # Use <= not <
print(i)
i += 1
# Mistake 3: Modifying a list while iterating
items = [1, 2, 3, 4, 5]
# WRONG: skips elements
# i = 0
# while i < len(items):
# if items[i] % 2 == 0:
# items.remove(items[i])
# i += 1
# CORRECT: iterate backwards
i = len(items) - 1
while i >= 0:
if items[i] % 2 == 0:
items.pop(i)
i -= 1
print(items) # [1, 3, 5]Practical Example: Number Guessing Game
python
"""
A number guessing game using while loops.
"""
import random
def guessing_game():
secret = random.randint(1, 100)
attempts = 0
max_attempts = 7
print("π― Guess the number (1-100)")
print(f"You have {max_attempts} attempts\n")
while attempts < max_attempts:
attempts += 1
remaining = max_attempts - attempts
try:
guess = int(input(f"Attempt {attempts}: "))
except ValueError:
print("Please enter a valid number")
attempts -= 1 # Don't count invalid input
continue
if guess == secret:
print(f"\nπ Correct! You got it in {attempts} attempts!")
return
elif guess < secret:
print(f"Too low! ({remaining} attempts left)")
else:
print(f"Too high! ({remaining} attempts left)")
print(f"\nπ Game over! The number was {secret}")
guessing_game()Summary
whileloops execute as long as a condition isTrue- Always ensure the loop condition will eventually become
False breakexits the loop immediatelycontinueskips the current iterationelseruns when the loop ends normally (nobreak)- Use
while Truewithbreakfor input validation and menu systems - Prefer
forloops when iterating over collections or known ranges - Common patterns: sentinel values, two-pointer, convergence, countdown
Next, we'll learn about Python functions.