Himanshu SharmaSoftware engineer
Let’s talk

Python Tutorial · Lesson 16 of 70

Python while loops: repeat until a condition changes

Use while loops to repeat Python code while a condition is true, with counters, running totals, sentinel values and ways to avoid infinite loops.

12 minControl flowUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonWrite while loops that count, accumulate totals and stop at the right moment, and avoid loops that never end.

After this lesson you can make a program repeat work for as long as it needs to. Repetition is what makes computers useful: they can do the same thing a thousand times without getting bored.

The basic shape

A while loop looks like an if. It has a condition, a colon and an indented block. The difference is that after the block finishes, Python goes back to the condition and checks it again:

python
count = 1
while count <= 3:
    print("Packing box", count)
    count = count + 1
print("All boxes packed")
result
Packing box 1
Packing box 2
Packing box 3
All boxes packed

Follow it step by step. count starts at 1. The condition count <= 3 is true, so the block runs, prints a line and adds 1. Python checks again with count equal to 2, then 3. After the third pass count is 4, the condition is false and Python moves on to the line after the loop.

Each trip through the block is called an iteration.

Three parts of a safe loop

A well-behaved while loop nearly always has three parts:

  1. Setup. A variable that starts with a sensible value (count = 1).
  2. Condition. A test using that variable (count <= 3).
  3. Update. A line inside the loop that changes the variable (count = count + 1).

If you forget the update, the condition never changes. That is the classic infinite loop. When that happens in a terminal, press Ctrl and C to stop the program.

Counting down

Loops can go in either direction:

python
seconds = 3
while seconds > 0:
    print(seconds)
    seconds -= 1
print("Lift off")
result
3
2
1
Lift off

seconds -= 1 is shorthand for seconds = seconds - 1.

Running totals

Another common pattern is to build up a total. Start it at zero before the loop and add to it each time round:

python
total = 0
day = 1
while day <= 5:
    total = total + day * 10
    day += 1
print("Total after five days:", total)
result
Total after five days: 150

Here each day adds 10 times the day number: 10, 20, 30, 40 and 50, which comes to 150.

Looping until something happens

Sometimes you do not know in advance how many repeats you need. A while loop is perfect for "keep going until a goal is reached". For example, how many months until savings pass a target?

python
savings = 0
months = 0
while savings < 1000:
    savings += 300
    months += 1
print("Months needed:", months)
print("Savings:", savings)
result
Months needed: 4
Savings: 1200

This kind of loop, where the number of repeats depends on the data, is where while is the right tool.

Sentinel values for input

A common design is to ask repeatedly until the user types a special value, such as an empty line, to say "I am finished". That special value is called a sentinel. The example below uses fixed answers, as in the input lesson, to show a conversation where the user types three prices and then presses Enter on an empty line:

python
total = 0
answer = input("Price (empty to finish): ")
while answer != "":
    total += int(answer)
    answer = input("Price (empty to finish): ")
print("Bill total:", total)
result
Price (empty to finish): 40
Price (empty to finish): 25
Price (empty to finish): 60
Price (empty to finish): 
Bill total: 125

The first input happens before the loop, so the condition has a value to test. The second input is the update step, giving the user a chance to end the loop.

A word about while True

You will often see this form:

python
while True:
    command = input("Type quit to stop: ")
    if command == "quit":
        break

The condition is always true, so the loop only ends when the break statement runs. The next lessons explain break properly. It is handy, but only use it when you are sure that something inside the loop will eventually stop it.

Tracing a loop by hand

The best way to understand a loop is to trace it with a small table. List the variables as columns and write a row for each pass. For the savings example, the columns would be months and savings, and you would write the values after each pass: 1 and 300, 2 and 600, 3 and 900, 4 and 1200. When the savings reach 1200 the condition fails, and you can see exactly why the answer is 4 months.

Tracing also finds mistakes. If your table shows the variable never moving toward making the condition false, you have found an infinite loop without even running it. If the first row already fails the test, you know the loop body will never run.

Make this a habit whenever a loop does not behave. A pencil and a few minutes beat guessing.

Common mistakes

  • Forgetting the update. The loop never ends. Check that each pass moves toward making the condition false.
  • Off by one. Using < when you meant <=, or the reverse, makes you repeat one time too few or too many. Test with a tiny case.
  • Starting the variable wrongly. If count starts at a value that already fails the condition, the loop body never runs.
  • Putting the update outside the loop. If it is not indented, it runs once, after the loop finishes, which is too late.
  • Comparing a string to a number. Text from input() must be converted with int() before a numeric comparison.

Exercise

A shop starts with 50 items in stock and sells 8 each day. Write a loop that prints the stock at the end of each day and stops once there are fewer than 8 items left, then prints how many days it lasted.

Show one possible answer
python
stock = 50
days = 0
while stock >= 8:
    stock -= 8
    days += 1
    print("Day", days, "stock:", stock)
print("Full days of selling:", days)
result
Day 1 stock: 42
Day 2 stock: 34
Day 3 stock: 26
Day 4 stock: 18
Day 5 stock: 10
Day 6 stock: 2
Full days of selling: 6

The loop only runs while there is enough stock for a whole day's sales. The stock goes 42, 34, 26, 18, 10 and 2, so it lasts six days.

Next: looping over a known set of values with for loops and range().

Key points

  • A while loop repeats its indented block as long as its condition is true.
  • Something inside the loop must change the condition, or the loop never ends.
  • Counters and running totals are the two most common patterns.
  • A sentinel value, such as an empty answer, lets the user end an input loop.

Check yourself

1. When does a while loop stop repeating?
2. What causes an infinite loop?
3. How many times does this print: n = 0, then while n < 3: print(n), n += 1?
4. In a running total loop, where should total start?