Python while Loop (With Examples)

While loops in Python repeat a block of code as long as a condition stays true. Python checks the condition before every pass, so a Python while loop is the right choice when you don’t know in advance how many times it should run.

while condition:
    # runs again and again while condition is True
    ...

The examples use US dollars and ZIP codes, and each one ran for real on Python 3.12.5; the screenshots are straight from the Command Prompt.

You’ll see the basic loop, input validation, loops over lists, while True with break, the else clause and the walrus operator, plus how to stop a loop that won’t end.

Python while loop syntax and a first example

This loop saves $150 a month until the balance reaches $1,000. Nothing says how many months that takes; the loop works it out:

balance = 0.00
month = 0

while balance < 1000:            # checked before every pass
    month += 1
    balance += 150
    print(f"month {month}: ${balance:,.2f}")

print("goal reached after", month, "months")

Output:

month 1: $150.00
month 2: $300.00
month 3: $450.00
month 4: $600.00
month 5: $750.00
month 6: $900.00
month 7: $1,050.00
goal reached after 7 months
Command Prompt output of a Python while loop adding 150 dollars a month until the balance reaches 1000
Seven passes, then the condition balance < 1000 became false and the loop stopped.

You need three parts: a variable set before the loop, a condition that tests it, and a line inside the loop that changes it. Forget the last part and your loop never ends.

Conditions can be anything that’s true or false. Python while loop conditions and while loops with multiple conditions go deeper on writing them.

Using a while loop to validate user input

This is where while loops shine. You don’t know how many tries someone will need, so you keep asking until the answer is valid:

zip_code = input("Enter a 5-digit ZIP code: ")

while not (zip_code.isdigit() and len(zip_code) == 5):
    print("That isn't a 5-digit ZIP code. Try again.")
    zip_code = input("Enter a 5-digit ZIP code: ")

print("Thanks! Shipping to", zip_code)

Output:

Enter a 5-digit ZIP code: abc
That isn't a 5-digit ZIP code. Try again.
Enter a 5-digit ZIP code: 7870
That isn't a 5-digit ZIP code. Try again.
Enter a 5-digit ZIP code: 78701
Thanks! Shipping to 78701
Command Prompt showing a Python while loop rejecting abc and 7870 and accepting the 5-digit ZIP code 78701
Two bad answers, then a valid ZIP code ends the loop.

I use this pattern for anything a person types in. Notice the input() appears twice: once before the loop, and once inside it for every retry; the while True version later avoids that.

Looping while a list isn’t empty

An empty list counts as false in Python, so while orders: keeps going exactly as long as there’s something left to process:

orders = ["A101", "A102", "A103"]

while orders:                    # an empty list is falsy, so this stops when it's empty
    current = orders.pop(0)
    print("shipping", current, "| still waiting:", len(orders))

print("queue empty")

Output:

shipping A101 | still waiting: 2
shipping A102 | still waiting: 1
shipping A103 | still waiting: 0
queue empty
Command Prompt output of a Python while loop popping orders from a list until it is empty
Each pass removed one order; the loop stopped on its own when the list ran out.

That’s a handy pattern for queues and to-do lists. If your queue gets large, collections.deque and popleft() are faster than pop(0) on a list.

When should you use a while loop instead of a for loop?

Use for when you’re going through a collection or a known range. Use while when the loop should stop on a condition and you can’t predict the count. Here’s a question only a while loop answers neatly:

# how many years until $10,000 doubles at 7% a year?
amount = 10_000.00
years = 0

while amount < 20_000:
    amount *= 1.07
    years += 1

print(f"{years} years -> ${amount:,.2f}")

Output:

11 years -> $21,048.52

Nobody knows the 11 up front; the loop discovers it. For loop vs while loop in Python compares the two in detail.

while True with break

while True loops forever on purpose and relies on break to get out. It’s often clearer than a condition at the top, because the exit test can sit wherever it makes sense:

count = 0

while True:                      # runs until something inside says stop
    count += 1
    if count % 2 == 0:
        continue
    print("odd:", count)
    if count >= 7:
        break

Output:

odd: 1
odd: 3
odd: 5
odd: 7

Here continue skips the even numbers and break stops at 7. Python break and continue covers both statements, including the continue mistake that freezes a while loop.

Python while loop with else

A while loop can have an else block. It runs when the condition becomes false, but not if the loop exits through break:

attempts = 0

while attempts < 3:
    attempts += 1
    print("checking the server, attempt", attempts)
    if attempts == 5:            # never true here, so no break
        break
else:
    print("loop ended normally (no break), after", attempts, "attempts")

Output:

checking the server, attempt 1
checking the server, attempt 2
checking the server, attempt 3
loop ended normally (no break), after 3 attempts

Think of it as “if the loop wasn’t broken out of”. It’s useful for search-style loops, where the else handles the “nothing found” case.

The same idea works on for loops. And if you’re after a loop that always runs at least once, Python has no do-while; the FAQ at the end shows the workaround.

The walrus operator in a while loop

Python 3.8 added :=, which assigns a value and tests it in the same expression. It removes the “read once before the loop, read again inside it” duplication:

states = iter(["TX", "CO", "NY", "", "CA"])

# := assigns and tests in one step (Python 3.8+)
while (code := next(states)) != "":
    print("state:", code)

print("stopped at the empty entry")

Output:

state: TX
state: CO
state: NY
stopped at the empty entry

I only reach for it where it genuinely shortens the code. If you or a teammate would have to stop and puzzle over the line, the plain two-line version is fine.

How to stop an infinite while loop

If a loop won’t end, press Ctrl+C in the terminal. Python raises KeyboardInterrupt and stops the program. In Jupyter, use the stop button or interrupt the kernel.

Then find out why it didn’t end. It’s almost always one of these:

  • The variable in the condition never changes inside the loop.
  • It changes, but in the wrong direction, so the condition can never become false.
  • A continue skips the line that updates the variable.
  • A float never exactly equals the target; use < or >= instead of !=.

Python while loop: quick reference

PatternCode
Basicwhile balance < 1000:
Until a list is emptywhile orders:
Run until breakwhile True: ... if done: break
Skip to the next passcontinue
Run code if no breakwhile ...: ... else: ...
Assign and testwhile (x := get()) != "":
Stop a runaway loopCtrl+C

Ready for more? These loop guides pick up where this one ends:

Frequently asked questions

What is a while loop in Python?

A loop that repeats its block as long as a condition is true. Python checks the condition before each pass and stops as soon as it’s false.

When should I use a while loop instead of a for loop?

When you can’t predict how many times the loop should run, such as waiting for valid input or a target balance. Use a for loop to go through a collection or a known range.

How do I stop a while loop in Python?

Make the condition false, or use break inside the loop. To stop a runaway loop from the keyboard, press Ctrl+C.

What does while True mean in Python?

It’s a loop whose condition is always true, so it runs until a break, a return or an exception ends it.

Does Python have a do-while loop?

No. Use while True with a break at the bottom to run the body at least once.

When does the else block of a while loop run?

When the condition becomes false. It’s skipped if the loop ends with break. The Python tutorial covers loop else clauses.