Lesson 5.2: while Loops
What You'll Learn
- How while loops differ from for loops
- How to write condition-based loops
- How to use counters and accumulators with while loops
- The sentinel value pattern for user input
- How to avoid and fix infinite loops
What Is a while Loop?
A while loop repeats a block of code as long as a condition is True.
Unlike a for loop (which iterates a known number of times), a while loop keeps going until
its condition becomes False.
True. The condition is checked before each iteration.
# Count from 1 to 5 count = 1 while count <= 5: print(count) count += 1 print("Done!")
Here is how it works step by step:
- Check: Is
count <= 5? (1 <= 5 is True) → run the body - Print 1, then count becomes 2
- Check: Is
count <= 5? (2 <= 5 is True) → run the body - ...continues until count is 6
- Check: Is
count <= 5? (6 <= 5 is False) → exit the loop
while vs. for: When to Use Which
Use a for loop when you know how many times to repeat (or you are iterating over a collection). Use a while loop when you do not know in advance and the loop depends on a condition.
for.
If the answer is "keep going until something happens" → use while.
Example: Halving Until Small
# Keep halving a number until it's less than 1 number = 100 while number >= 1: print(number) number /= 2 print(f"Final value: {number}")
Infinite Loops (and How to Avoid Them)
If the condition never becomes False, the loop runs forever. This is called an infinite loop, and it will freeze your program.
# INFINITE LOOP - DO NOT RUN THIS! # count = 1 # while count <= 5: # print(count) # # Forgot to increment count! # # count never changes, so count <= 5 is always True # FIXED version: count = 1 while count <= 5: print(count) count += 1 # This makes count eventually > 5
Three common causes of infinite loops:
- Forgetting to update the loop variable
- Updating the variable in the wrong direction
- A condition that can never become False
Input Validation with while Loops
One of the most practical uses of while loops is asking the user for input until they give a valid answer.
Pattern: Keep Asking Until Valid
# Ask for a positive number number = -1 # Start with an invalid value while number < 0: number = int(input("Enter a positive number: ")) if number < 0: print("That's negative! Try again.") print(f"You entered: {number}")
Pattern: Password Attempts
correct_password = "python123" attempts = 0 max_attempts = 3 while attempts < max_attempts: guess = input("Enter password: ") attempts += 1 if guess == correct_password: print("Access granted!") break # Exit the loop early else: remaining = max_attempts - attempts if remaining > 0: print(f"Wrong! {remaining} attempts left.") else: print("Account locked.")
Sentinel Values
A sentinel value is a special value that signals the loop to stop. It is commonly used when processing a series of user inputs.
# Add up numbers until the user types 'done' total = 0 count = 0 print("Enter numbers to add up. Type 'done' to finish.") while True: user_input = input("Number: ") if user_input.lower() == "done": break total += float(user_input) count += 1 if count > 0: print(f"Sum: {total}") print(f"Average: {total / count}") else: print("No numbers entered.")
Practical Examples
Example: Countdown Timer
seconds = 5 while seconds > 0: print(f"{seconds}...") seconds -= 1 print("Go!")
Example: Guessing Game
secret = 42 guess = 0 attempts = 0 while guess != secret: guess = int(input("Guess the number (1-100): ")) attempts += 1 if guess < secret: print("Too low!") elif guess > secret: print("Too high!") else: print(f"Correct! You got it in {attempts} attempts.")
Check Your Understanding
How many times will "Hello" be printed?
x = 10 while x > 1: print("Hello") x = x // 2
Answer: 4 times
x starts at 10. Each iteration: x = x // 2 (integer division).
x=10: print Hello, x becomes 5
x=5: print Hello, x becomes 2
x=2: print Hello, x becomes 1
x=1: condition 1 > 1 is False, loop ends. Wait — let me recheck. x=10 → 5 → 2 → 1. That is 3 prints, not 4.
Corrected: 3 times. x goes 10 → 5 → 2 → 1. When x is 1, the condition 1 > 1 is False.
Key Takeaways
- while loops repeat as long as a condition is True
- Use while loops when you do not know the number of iterations in advance
- Always ensure the condition will eventually become False to avoid infinite loops
- Input validation is one of the most common uses of while loops
- Sentinel values signal the loop to stop
- If your program hangs, press Ctrl+C to stop an infinite loop