Control Flow - While Loops
Learn to repeat code as long as a condition is true
What You'll Learn
- What while loops are
- When to use while vs for
- Avoiding infinite loops
- Using break and continue
What is a While Loop?
A while loop repeats code as long as something is True.
Format:
while condition:
# do thisExample:
count = 0
while count < 5:
print(count)
count += 1Output:
0
1
2
3
4
While vs For Loops
Use for when: You know how many times to repeat
# Print 5 times
for i in range(5):
print("Hello")Use while when: You don't know how many times
# Keep asking until correct
password = ""
while password != "secret":
password = input("Enter password: ")Simple Examples
Example 1: Countdown
count = 5
while count > 0:
print(count)
count -= 1
print("Blast off!")Output:
5
4
3
2
1
Blast off!
Example 2: Sum until limit
total = 0
number = 1
while total < 20:
total += number
print(f"Added {number}, total is {total}")
number += 1Example 3: User menu
choice = ""
while choice != "quit":
print("1. Start")
print("2. Help")
print("Type 'quit' to exit")
choice = input("Choose: ")Infinite Loops (Dangerous!)
Loop that never stops:
# Don't run this!
while True:
print("Forever!")This runs forever! Press Ctrl+C to stop.
How to avoid: Always change the condition:
# Good - stops eventually
count = 0
while count < 5:
print(count)
count += 1 # Changes condition!Using break
Stop the loop early:
count = 0
while True:
print(count)
count += 1
if count >= 5:
break # Stop hereExample: Find number
numbers = [3, 7, 2, 9, 5]
index = 0
while index < len(numbers):
if numbers[index] == 9:
print("Found 9!")
break
index += 1Using continue
Skip to next iteration:
count = 0
while count < 5:
count += 1
if count == 3:
continue # Skip 3
print(count)
# Shows: 1, 2, 4, 5Practice Examples
Example 1: Guess the number
secret = 7
guess = 0
while guess != secret:
guess = int(input("Guess (1-10): "))
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print("Correct!")Example 2: Build total
total = 0
number = 1
while number <= 10:
total += number
number += 1
print(f"Sum of 1-10: {total}")
# Shows: Sum of 1-10: 55Example 3: Login attempts
correct_password = "1234"
attempts = 0
max_attempts = 3
while attempts < max_attempts:
password = input("Enter password: ")
if password == correct_password:
print("Login successful!")
break
else:
attempts += 1
remaining = max_attempts - attempts
print(f"Wrong! {remaining} attempts left")
if attempts == max_attempts:
print("Account locked!")While with Lists
Process items one by one:
items = ["apple", "banana", "orange"]
index = 0
while index < len(items):
print(items[index])
index += 1Remove items:
numbers = [1, 2, 3, 4, 5]
while numbers: # While list is not empty
num = numbers.pop() # Remove last item
print(f"Removed: {num}")Real-World Examples
Example 1: ATM withdrawal
balance = 1000
while True:
print("Balance: $" + str(balance))
amount = int(input("Withdraw (0 to quit): "))
if amount == 0:
break
if amount > balance:
print("Insufficient funds!")
else:
balance -= amount
print("Withdrew $" + str(amount))
print("Thank you!")Example 2: Input validation
age = -1
while age < 0 or age > 120:
age = int(input("Enter age (0-120): "))
if age < 0 or age > 120:
print("Invalid age!")
print(f"Your age is {age}")Example 3: Shopping cart
cart = []
while True:
item = input("Add item (or 'done'): ")
if item == "done":
break
cart.append(item)
print(f"Added {item}")
print("Your cart:")
for item in cart:
print(f"- {item}")Common Mistakes
Mistake 1: Forgetting to change condition
# Wrong - infinite loop!
count = 0
while count < 5:
print(count)
# Forgot: count += 1
# Correct
count = 0
while count < 5:
print(count)
count += 1Mistake 2: Wrong condition
# This never runs
count = 10
while count < 5:
print(count)
# count is already 10!Mistake 3: Forgetting break
# Infinite loop
while True:
print("Hello")
# Need break somewhere!When to Stop Loops
By count:
count = 0
while count < 10:
# ...
count += 1By condition:
found = False
while not found:
# ...
if something:
found = TrueBy user input:
while True:
answer = input("Continue? (y/n): ")
if answer == "n":
breakQuick Reference
Basic while:
while condition:
# do thisForever (use with break):
while True:
# do this
if something:
breakStop early:
breakSkip one:
continueSummary
- while loops repeat while condition is True
- Always change the condition to avoid infinite loops
- Use break to stop early
- Use continue to skip one iteration
- Good for unknown number of repetitions
- Use for loops when count is known
What's Next?
Now let's learn how to create reusable code with functions!