Python with AI Tutorial · Chapter 18 of 48
A Python while loop repeats a block of code for as long as a condition stays True. Python checks the condition before every pass, so the loop can run zero times, a few times or indefinitely. You control it with break, continue and an optional else clause that runs when the loop finishes normally.
Basic while loop
Write while, a condition and a colon. Something inside the block must eventually make the condition false, otherwise the loop never stops.
week = 1
while week <= 4:
print(f"Week {week} report sent")
week += 1
print("Month complete")
Output: Week 1 report sent Week 2 report sent Week 3 report sent Week 4 report sent Month complete
The line week += 1 is the counter update. Forget it and week stays at 1 forever.
Ctrl+C in the terminal to stop it. Before running any while loop, ask yourself which line changes the variable in the condition.Because the test happens before each pass, a while loop whose condition is already false does nothing at all. If week started at 5 in the example above, no reports would be printed and Python would move straight on to the final line. This zero-iteration behaviour is a feature: it means you rarely need a separate check before the loop.
Looping until a target is reached
While loops shine when you do not know in advance how many iterations you need. Here we keep compounding a savings balance until it crosses a goal.
balance = 10000
rate = 0.06
years = 0
while balance < 15000:
balance = balance * (1 + rate)
years += 1
print(f"Goal reached after {years} years: {balance:,.2f}")
Output: Goal reached after 7 years: 15,036.30
This kind of loop is awkward to write as a for loop because the number of years is the answer we are looking for, not something we know beforehand. Whenever the stopping point depends on a value that changes inside the loop, reach for while.
Loop control keywords
Three keywords change how a while loop behaves.
| Keyword | What it does | Typical use |
|---|---|---|
break |
Leaves the loop immediately | Stop once a match is found |
continue |
Skips the rest of this pass and re-tests the condition | Ignore invalid records |
else |
Runs once when the condition becomes false, but not after break |
Report “nothing found” |
pass |
Does nothing; a placeholder for an empty body | Code still to be written |
break: stop early
break ends the loop at once, even if the condition is still true. It is common in search loops.
invoices = [1001, 1002, 1003, 1004, 1005]
amounts = [250, 900, 4800, 120, 60]
i = 0
while i < len(invoices):
if amounts[i] > 4000:
print(f"First large invoice: {invoices[i]} ({amounts[i]})")
break
i += 1
Output: First large invoice: 1003 (4800)
continue: skip one pass
continue jumps straight back to the condition check. Make sure the counter is updated before continue, or you create an infinite loop.
readings = [42, -1, 38, -1, 45]
i = 0
total = 0
count = 0
while i < len(readings):
value = readings[i]
i += 1
if value < 0:
continue # -1 means the sensor failed
total += value
count += 1
print(f"Average of valid readings: {total / count:.1f}")
Output: Average of valid readings: 41.7
Give the assistant a while loop that uses continue and ask it to find the infinite-loop bug when the increment is placed after the continue.
This Python while loop is supposed to skip negative numbers but it never finishes: i = 0; while i < len(data): if data[i] < 0: continue; total += data[i]; i += 1. Explain exactly why it hangs and show two corrected versions.
while…else
The else block runs when the loop condition becomes false. It is skipped if the loop ended with break, which makes it a clean way to say “we searched everything and found nothing”.
employees = ["Asha", "Ben", "Chloe"]
target = "Dev"
i = 0
while i < len(employees):
if employees[i] == target:
print(f"{target} found at position {i}")
break
i += 1
else:
print(f"{target} is not on the payroll")
Output: Dev is not on the payroll
The while True pattern
Sometimes the exit condition is easier to express in the middle of the loop. Write while True: and use break to leave. This is the standard shape for menus and retry logic.
queue = ["order 501", "order 502", "order 503"]
processed = 0
while True:
if not queue:
break
item = queue.pop(0)
processed += 1
print(f"Processing {item}")
print(f"{processed} orders done, queue empty")
Output: Processing order 501 Processing order 502 Processing order 503 3 orders done, queue empty
Some programmers dislike while True because the exit is hidden inside the body. It is perfectly acceptable Python, but keep the break near the top of the block where readers can find it, and avoid having more than one or two exit points in the same loop.
Nested while loops
A while loop can contain another loop. The inner loop runs completely for every pass of the outer loop. Here we print a small quarter-by-month grid.
quarter = 1
while quarter <= 2:
month = 1
while month <= 3:
print(f"Q{quarter}-M{month}", end=" ")
month += 1
print()
quarter += 1
Output: Q1-M1 Q1-M2 Q1-M3 Q2-M1 Q2-M2 Q2-M3
Notice that month is reset to 1 inside the outer loop. If it were set only once at the top, the inner loop would run for the first quarter only.
Ask for a retry loop with a maximum attempt count and a while…else clause, then read the explanation of when else runs.
Write a Python while loop that simulates retrying a failed payment up to 3 times. Use a list like results = ["fail", "fail", "ok"] to stand in for the gateway, break on the first "ok", and use the while...else clause to print "Payment failed after 3 attempts" only when every attempt failed. Comment each line.
Nested loops multiply: an outer loop of 1,000 passes and an inner loop of 1,000 passes means one million iterations. For small business datasets that is instant, but if a report starts to feel slow, look at the nesting first and consider whether a dictionary lookup could replace the inner loop.
Common mistakes
- Never updating the variable in the condition, which creates an infinite loop.
- Placing the counter increment after a
continueso it is skipped. - Using a while loop to walk through a list when a
forloop would be shorter and safer. - Expecting the
elseblock to run afterbreak; it only runs when the condition itself becomes false. - Testing a floating-point value with
==as the exit condition; use<or>=instead.
Exercise
A warehouse starts with 120 units. Each day it ships 17 units. Use a while loop to count how many full days of shipping are possible before stock would go negative, and print the remaining units afterwards.
Show answer
stock = 120
shipment = 17
days = 0
while stock >= shipment:
stock -= shipment
days += 1
print(f"{days} days of shipping, {stock} units left")
Output: 7 days of shipping, 1 units left
Related chapters
FAQ
When should I use a while loop instead of a for loop in Python?
Use a while loop when you do not know how many iterations are needed in advance, such as waiting for a balance to reach a target or retrying until success. Use a for loop to walk through a known sequence.
How do I stop an infinite while loop in Python?
Press Ctrl+C in the terminal to raise a KeyboardInterrupt. To prevent it, make sure the loop body changes the variable used in the condition or includes a break.
What does else do in a Python while loop?
The else block runs once when the loop condition becomes false. It does not run if the loop was exited with break, which makes it useful for reporting that a search found nothing.
Working with spreadsheets too? Ready-made Excel, Google Sheets and Power BI templates are at NextGenTemplates.com.
Chapter 18 of 48 · Python with AI: all 48 chapters



