How to Use a While Loop in Python

What you'll build or solve

You'll use a while loop to repeat code until a condition changes.

When this approach works best

A while loop works well when you:

  • Repeat until something becomes true or false, like waiting for a value to reach a limit.
  • Run a loop with an exit condition inside the body, like stopping on a sentinel value.
  • Keep processing while a collection has items, like handling tasks until a list is empty.

Avoid while loops when you already know the number of iterations. A for loop is usually clearer for "do this 10 times" or "loop over each item in a list."

Prerequisites

  • Python installed
  • You know what a boolean condition is

Step-by-step instructions

1) Write a basic while loop

A while loop runs as long as its condition stays True.

count = 1

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

What to look for:

Something inside the loop must change. Otherwise, the condition never becomes False.


2) Control the loop with break and continue

Use break to stop early, and continue to skip to the next iteration.

n = 0

while True:
    n += 1

    if n == 2:
        continue  # skip printing 2

    if n == 4:
        break  # stop the loop

    print(n)

What to look for:

while True is fine when break defines the exit. Keep the exit path obvious.


Examples you can copy

Example 1: Countdown timer

seconds = 5

while seconds > 0:
    print(seconds)
    seconds -= 1

print("Done")

Example 2: Keep asking until the user types "quit"

while True:
    text = input("Type something (or quit): ").strip()

    if text.casefold() == "quit":
        break

    print("You typed:", text)

Example 3: Validate user input

while True:
    text = input("Enter a number (1-5): ").strip()

    if text.isdigit():
        value = int(text)
        if 1 <= value <= 5:
            break

    print("Try again.")

Example 4: Track attempts with a counter

max_attempts = 3
attempts = 0

while attempts < max_attempts:
    password = input("Password: ")

    if password == "open-sesame":
        print("Welcome!")
        break

    attempts += 1
    print("Wrong password.")

if attempts == max_attempts:
    print("Locked out.")

Example 5: Process items until the list is empty

tasks = ["email", "build", "deploy"]

while tasks:
    task = tasks.pop(0)
    print("Working on:", task)

Example 6: Read lines until a blank line

lines = []

while True:
    line = input("Line (blank to stop): ")
    if line == "":
        break
    lines.append(line)

print("Saved", len(lines), "lines")

Common mistakes and how to fix them

Mistake 1: Creating an infinite loop by forgetting to update state

What you might do

count = 1

while count <= 3:
    print(count)

Why it breaks

count never changes, so the condition stays true forever.

Fix

count = 1

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

Mistake 2: Expecting continue to stop the loop

What you might do

n = 0

while n < 3:
    n += 1
    if n == 2:
        continue
    print(n)

Why it breaks

continue skips the rest of the current iteration. Then the loop runs again.

Fix

Use break when you need to stop:

n = 0

while n < 3:
    n += 1
    if n == 2:
        break
    print(n)

Troubleshooting

If your program never ends, add a print() inside the loop to confirm the condition changes, or add a counter limit while debugging.

If break never runs, print the values your if checks to see what differs from what you expect.

If input checks fail for "Quit" vs "quit", compare with .casefold() or .lower() on both sides.

If a counter-based loop stops too early, check where you increment the counter. Increment on failed attempts, not on success.

If your loop depends on a list, use while items: to stop when the list becomes empty.


Quick recap

  • Use while condition: to repeat code until the condition becomes false.
  • Change something in the loop so the condition can fail.
  • Use break to exit early and continue to skip an iteration.
  • while True works well when an explicit break defines the exit.
  • Add quick prints or a counter when debugging loops that do not stop.