Skip to content
Hands-on Mentor
ENTR
Back to blog

Python while loop: how it works, with examples

A Python while loop repeats a block of code as long as a condition is true. Learn the syntax, break and continue, and how to fix an infinite loop.

5 min read

A Python while loop repeats a block of code as long as a condition is true. Python checks the condition before every round. When the condition becomes false, the loop stops and the program continues with the next line. Use while when you do not know in advance how many repeats you need.

The examples use Corner Café in Port Alder. Ada runs the café, and she wants to save for a new coffee grinder.

What is the syntax of a while loop?

Write while, a condition and a colon. The indented lines below are the body of the loop:

count = 3
while count > 0:
    print(count)
    count -= 1
print("done")
Output3
2
1
done

Python works in this order:

1. Check the condition (count > 0).

2. If it is true, run the body, then go back to step 1.

3. If it is false, skip the body and continue after the loop.

The line count -= 1 is important. It changes the value that the condition looks at. Without a change like that, the loop would never end.

When should you use while instead of for?

Use for when you have a sequence to walk through, like a list of orders or a range of numbers. Use while when you only know the stopping condition.

Ada earns an average of $17.50 per day. How many days until she has saved $50? We do not know the number of days, only the goal:

daily_revenue = 17.50
goal = 50.00
total = 0
days = 0
while total < goal:
    total += daily_revenue
    days += 1
print(f"{days} days, ${total:.2f}")
Output3 days, $52.50

After two days the total is $35.00, which is below the goal, so the loop runs a third time. A for loop would need you to guess the number of days first.

How do you stop a while loop with break?

break leaves the loop at once, even if the condition is still true. A common pattern is while True: with a break inside, for jobs where you only know the stop signal while you are working. Here, a list of orders ends with a "stop" command:

orders = ["latte", "tea", "stop", "brownie"]
index = 0
while True:
    item = orders[index]
    if item == "stop":
        break
    print("making", item)
    index += 1
print("stopped at index", index)
Outputmaking latte
making tea
stopped at index 2

The "brownie" order after "stop" is never made, because the loop ended at index 2.

How do you skip one round with continue?

continue skips the rest of the current round and goes back to the condition. It is common with for, and it works in while too. Take care in while: if continue jumps over the line that changes your counter, you create an infinite loop.

Here is a simple use in a for loop. Ada adds up a list of items, and one item is not on the menu:

prices = {"latte": 4.25, "tea": 1.25, "brownie": 3.75, "lemonade": 3.25, "water": 0.75}
total = 0
for item in ["latte", "tea", "cookie", "water"]:
    if item not in prices:
        print("skipping", item)
        continue
    total += prices[item]
print(f"${total:.2f}")
Outputskipping cookie
$6.25

What is an infinite loop and how do you fix it?

An infinite loop is a loop whose condition never becomes false. The program keeps running until you stop it. This is the most common while mistake:

Outputi = 0
while i < 3:
    print(i)

This prints 0 forever, because nothing changes i. Run it in a browser lesson and you have to stop the program. When a while loop does not end, ask three questions:

1. Which variable does the condition use?

2. Is there a line inside the loop that changes that variable?

3. Does the change move the value toward the stopping point (up when you wait for a large value, down when you wait for a small one)?

For the example above, the fix is one line:

i = 0
while i < 3:
    print(i)
    i += 1

While you are learning, add a safety counter. It stops the loop after a fixed number of rounds, even when your logic is wrong:

total = 0
rounds = 0
while total < 10:
    rounds += 1
    if rounds > 100:
        print("safety stop")
        break
print(rounds)
Outputsafety stop
101

Here total never changes, so the condition total < 10 stays true. The safety counter ended the loop after 100 full rounds, and rounds shows 101 because break runs on the next count. Without it, the program would not stop.

What other mistakes should you watch for?

  • Changing the value in the wrong direction. If count goes up when you wait for it to reach 0, the loop never ends.
  • Using `==` for a number that jumps over the target. With stock 12 and sales of 5, the stock goes 12, 7, 2, then below zero. A condition stock != 0 never becomes false. Prefer > or <.
  • Forgetting the colon or the indentation. Python raises a SyntaxError or an IndentationError.
  • Putting the update after `continue`. The update never runs for that round.

What to read next

  • Practice in your browser: [while, break and continue](/learn/python/while-break-continue) and [The for loop and range](/learn/python/for-range)
  • Related post: [Python for loop](/blog/python-for-loop)
  • When something breaks: [Common Python errors](/blog/common-python-errors)
  • Browse the whole course: [Python course](/courses/python)
  • #python
  • #while loop
  • #loops
  • #infinite loop
All posts