Topic 2.3
Repeating with while
In one line
A while loop repeats a block of code for as long as its condition stays True. You must make something inside the loop change the condition, or the loop never ends.
Think of it like this
Filling a glass of water. "While the glass is not full, keep pouring." You look at the glass, decide, pour a little, and look again. You do not count the pours in advance; you keep checking the condition. A while loop is exactly this: check, do the work, check again.
Words you'll meet
New words in this topic, in plain English. Come back here whenever one feels fuzzy.
- Loop
- Code that repeats.
- Iteration
- One pass through the body of a loop.
- Counter
- A variable that counts passes or steps, such as
countori. - Infinite loop
- A loop that never ends because its condition never becomes False.
- Sentinel
- A special value that signals "stop", such as
-1at the end of a list of scores. - break
- A statement that leaves the nearest loop immediately (Topic 2.5).
- Ctrl+C
- The keys that interrupt a running program in a terminal. Python raises
KeyboardInterrupt. - List (preview)
- Several values kept in order inside square brackets, such as
[4, 8, 15]. Phase 4 teaches lists properly; here we only read from them.
Step by step
01A countdown: the three parts of a counter loop
Set the counter, test it, change it. Python prints 3, 2, 1, then at count = 0 the test 0 > 0 is False and the loop ends. "Liftoff" is outside the block, so it runs once, at the end.
count = 3 # 1. set
while count > 0: # 2. test
print("Countdown:", count)
count = count - 1 # 3. change
print("Liftoff")02Accumulating a total
A very common use: keep a running total in one variable, and a counter in another. Each pass adds the current number to the total and moves the counter on. After the loop, total holds 1 + 2 + 3 + 4 + 5 = 15.
total = 0
n = 1
while n <= 5:
total += n
n += 1
print("Sum of 1..5:", total)03When you don't know how many times
How many years until 100 grows past 150 at 10% a year? You cannot say without trying, so a while loop fits: keep going until the goal is reached. The answer is 5 years (balance 161.05). balance * 1.1 adds 10% each year, and round(balance, 2) shows the number with 2 decimal places.
balance = 100
years = 0
while balance < 150:
balance = balance * 1.1
years += 1
print("Years:", years, "Balance:", round(balance, 2))04The infinite loop
This loop never changes count, so count < 3 is always True. It prints 0 forever. Whenever you write a while, find the line that makes the condition eventually False.
Do not run this one: it is shown to teach you what to look for.
count = 0
while count < 3:
print(count)
# forgot: count += 1 <- nothing changes the condition05A sentinel loop
The list is read from the front, one item at a time, with index pointing at the current item (numbers[0] is the first). The loop stops when it meets -1, the sentinel, so 99 is never added. The result is 4 + 8 + 15 = 27.
numbers = [4, 8, 15, -1, 99]
index = 0
total = 0
while numbers[index] != -1:
total += numbers[index]
index += 1
print("Sum before -1:", total)06while True with break
while True: means "repeat forever", and the break is the only way out. Here the test happens in the middle of the block (after taking a guess), which is why this shape is clearer than putting a condition on the while line. The guesses come from a fixed list so the example is repeatable.
guesses = [3, 9, 5, 7]
target = 5
attempts = 0
while True:
guess = guesses[attempts]
attempts += 1
if guess == target:
print("Found", target, "after", attempts, "tries")
break
print("Wrong:", guess)07Zero iterations, and the float trap
If the condition is False the first time, the block never runs and nothing is printed. And comparing floats with != is dangerous because of rounding (Topic 1.3).
balance = 200
while balance < 150:
print("never printed") # zero iterations
x = 0.0
# while x != 1.0: # never ends: 0.1 added 10 times is
# x += 0.1 # 0.9999999999999999, not 1.0
while x < 1.0:
x += 0.1 # use < instead of !=Try it yourself
- 1
Count up
Change the countdown to count up from 1 to 5. You need to change the starting value, the condition and the update. Run it and check that it prints 1 to 5 and then stops.
- 2
Double until big
Start
value = 1andsteps = 0. Whilevalueis at most 1000, double it and add one tosteps. Predict the finalvalueandstepsbefore you run (powers of two: 1, 2, 4, 8 ...). - 3
Spot the infinite loop (safely)
Read the third code block and write down the one line that would fix it. Then add that line to a copy and run the fixed version.
Code & diagrams
Change the start of the countdown to 5, and change the target balance to 200. Predict the number of years first.
Expected output
Countdown: 3
Countdown: 2
Countdown: 1
Liftoff
Sum of 1..5: 15
Years: 5 Balance: 161.05Move the 5 later in the guesses list and see how the number of tries changes. What happens if the target is not in the list at all? (The program will stop with an error: why?)
Expected output
Sum before -1: 27
Wrong: 3
Wrong: 9
Found 5 after 3 triesThe counter never changes, so the condition is always True. Never put a loop like this in a runnable example: it would print forever.
count = 0
while count < 3:
print(count)
# count += 1 is missingOutput
0
0
0
... (forever, until you press Ctrl+C)Break it on purpose
Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.
Break #1
Forget to update the counter
Delete the line count += 1 from a counting loop and run it in a terminal.
count = 0
while count < 3:
print(count)Myth vs fact
Myth
A while loop checks its condition continuously, so it stops the moment the condition becomes False.
Fact
The condition is tested only at the top, before each iteration. If it becomes False in the middle of the block, the rest of that block still runs.
Myth
while True is bad style.
Fact
It is the normal, clear way to write "repeat until a break" when the exit test happens in the middle of the block. It is bad only when there is no break or return that can end it.
Myth
Use while loops for everything you repeat.
Fact
When you have a known list or count, for (Topic 2.4) is shorter and cannot forget the counter update. Use while when the number of repeats is not known in advance.
Pro corner
Extra depth for experienced readers. New to this? Skip it for now and come back later.
- ▸
Programs that run forever on purpose (servers, bots, a game loop) are written as
while True:with a clean way out, such as a shutdown flag or an exception handler. The loop body does one unit of work and returns to waiting. - ▸
A retry loop is a
whileloop:attempts = 0, loop whileattempts < 3, try the request,breakon success. Real code adds a delay that grows between attempts (exponential backoff, Topic 15.2), which is how AI API clients cope with rate limits. - ▸
Every loop should have an upper bound you can name, even if only a maximum number of attempts. An unbounded loop that waits for an outside system (a network, a file) is a classic cause of hung jobs in production.
- ▸
The
whilecondition is re-evaluated on every pass, so keep it cheap and free of side effects. Calling a function in the condition (while compute() > 0) runs it every iteration, and the walrus operator (Topic 2.9) can store its result. - ▸
Python has no
do ... whileloop (run the body once, then test). The idiom iswhile True:with the work first andif not condition: breakat the end. Interviewers like this question because it checks that you know the loop forms rather than the syntax of one language. - ▸
Float counters drift:
x = 0.0withwhile x < 1.0: x += 0.1runs 11 times, not 10, because ten additions give 0.9999999999999999, which is still below 1.0. Count with an integer and compute the float from it (x = step * 0.1), or usemath.isclose(Topic 1.3). For a bounded retry,for attempt in range(3):with a loopelsefor the "all attempts failed" case is safer than a hand-madewhilecounter.
Remember this
- 1
The shape is
while condition:followed by an indented block, just likeif. The difference is what happens at the end of the block. After anifblock Python moves on. After awhileblock Python jumps back to the condition and tests it again. One pass through the block is called an iteration. When the condition is False at the check, the loop is over and Python continues with the first line after the block. - 2
The most common pattern is a counter: set it before the loop, test it in the condition, and change it inside the block.
count = 3,while count > 0:,count = count - 1. Three parts, and if you forget the third, the condition never changes. You can write the update ascount -= 1(Topic 1.7). - 3
A loop whose condition never becomes False is an infinite loop. It is a bug, not an error: Python does not complain, the program just never finishes (or prints forever). The usual causes are forgetting the update, updating the wrong variable, or a condition that can never be False. When you read a
whileloop, ask: "what inside the block changes the thing the condition looks at?" If nothing does, it is an infinite loop. In a terminal press Ctrl+C to stop it; the Run button on this page stops a program that runs too long. - 4
The condition is tested before the first iteration, so a
whileloop can run zero times.while balance < 150:does nothing at all if the balance is already 150 or more. This is useful: "do it as many times as needed, including none". - 5
A sentinel loop repeats until a special value (the sentinel) appears, such as
-1meaning "end of data". A related pattern iswhile True:(an intentional infinite loop) with abreakinside that leaves the loop when the goal is reached. It is the clearest way to write "keep trying until it works" when the test comes in the middle of the block (Topic 2.5 coversbreak). - 6
Use
whilewhen you do not know in advance how many repeats you need (read until the data ends, retry until success, grow until a limit). When you have a known list of items or a known count, aforloop (Topic 2.4) is shorter and safer, because it cannot forget the counter update. Be careful with decimal numbers (floats, Topic 1.3).while x != 1.0can run forever, because0.1added ten times is not exactly1.0. Use<or<=instead.
Explain it without notes
How does a while loop work, step by step?
What is an infinite loop and how do you spot one while reading code?
What is a sentinel loop? Give an example.
When would you choose while over for?
Practice
Use a while loop to print the numbers 1 to 5, one per line.
Start with value = 1 and steps = 0. Double value while it is at most 1000, counting the steps. Print value and steps.
A list data = [5, 10, 0, 7] ends data at the first 0. Use a sentinel while loop to add up the numbers before the 0 and print Total: 15.
Trade-offs
- ↔
while vs for.
whileis flexible (any condition) but you must manage the counter yourself.foris safer when the items are known. - ↔
Condition on the while line vs while True + break. A condition on the line is the simplest reading.
while Trueis clearer when the exit test is in the middle of the work.
Done when you can
Done when you can write a counter loop with a start, a test and an update.
Done when you can point to the line that ends a loop, or find that none exists.
Done when you can write a sentinel loop and a
while Trueloop withbreak.Done when you can explain why a
whileloop can run zero times.Done when you can say why
!=on floats is dangerous in a loop condition.