Learn Without Walls
← Previous Lesson Lesson 2 of 4 Next Lesson →

Lesson 5.2: while Loops

What You'll Learn

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.

while loop: Repeats a block of code as long as the specified condition evaluates to True. The condition is checked before each iteration.
# Count from 1 to 5
count = 1

while count <= 5:
    print(count)
    count += 1

print("Done!")
1 2 3 4 5 Done!

Here is how it works step by step:

  1. Check: Is count <= 5? (1 <= 5 is True) → run the body
  2. Print 1, then count becomes 2
  3. Check: Is count <= 5? (2 <= 5 is True) → run the body
  4. ...continues until count is 6
  5. 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.

Rule of thumb: If you can answer "how many times?" before the loop starts → use 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}")
100 50.0 25.0 12.5 6.25 3.125 1.5625 Final value: 0.78125

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.

Danger: Infinite Loop! If your program seems stuck, press Ctrl+C to stop it. Always make sure your loop condition will eventually become False.
# 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:

  1. Forgetting to update the loop variable
  2. Updating the variable in the wrong direction
  3. 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.

Sentinel value: A predefined value that, when entered, tells the program to stop accepting input and exit the loop.
# 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!")
5... 4... 3... 2... 1... 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

← for Loops Lesson 2 of 4 Next: break, continue, pass →