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:
count = 1
while count <= 3:
print("Packing box", count)
count = count + 1
print("All boxes packed")Packing box 1
Packing box 2
Packing box 3
All boxes packedFollow 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:
- Setup. A variable that starts with a sensible value (
count = 1). - Condition. A test using that variable (
count <= 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:
seconds = 3
while seconds > 0:
print(seconds)
seconds -= 1
print("Lift off")3
2
1
Lift offseconds -= 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:
total = 0
day = 1
while day <= 5:
total = total + day * 10
day += 1
print("Total after five days:", total)Total after five days: 150Here 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?
savings = 0
months = 0
while savings < 1000:
savings += 300
months += 1
print("Months needed:", months)
print("Savings:", savings)Months needed: 4
Savings: 1200This 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:
total = 0
answer = input("Price (empty to finish): ")
while answer != "":
total += int(answer)
answer = input("Price (empty to finish): ")
print("Bill total:", total)Price (empty to finish): 40
Price (empty to finish): 25
Price (empty to finish): 60
Price (empty to finish):
Bill total: 125The 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:
while True:
command = input("Type quit to stop: ")
if command == "quit":
breakThe 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
countstarts 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 withint()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
stock = 50
days = 0
while stock >= 8:
stock -= 8
days += 1
print("Day", days, "stock:", stock)
print("Full days of selling:", days)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: 6The 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.