The while Loop
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)When an action needs to repeat as long as a condition holds true, use a while loop. It checks the condition before every iteration.
Basic while loop structure
While loop is a statement that repeats its body again and again as long as its condition is True. The condition is checked before every round, so the body can run zero times.
A while loop checks its condition at the start of each cycle. If the condition is True, the body runs.
count = 1while count <= 3: print(f"Iteration {count}") count += 1Example 1 · Tickets waiting in a queue
tickets = 4while tickets > 0: print(f"Tickets waiting: {tickets}") tickets -= 1print("Queue is empty")Tickets waiting: 4 Tickets waiting: 3 Tickets waiting: 2 Tickets waiting: 1 Queue is empty
What this code does
tickets > 0is checked before every round, starting with 4.tickets -= 1lowers the value, so after 4 rounds the condition is False.- The last
printis not indented, so it runs once, after the loop.
The console displays Iterations 1, 2, and 3. When count reaches 4, the condition becomes False and the loop exits.
State updates and infinite loops
Infinite loop is a loop whose condition never becomes False, so it never stops by itself. It usually happens when nothing in the body changes the values the condition uses.
Every while loop must modify its controlling condition inside the loop body, otherwise it will run indefinitely.
countdown = 3while countdown > 0: print(countdown) countdown -= 1print("Launch!")Example 2 · Filling orders from stock
stock = 20orders = 0while stock >= 6: stock -= 6 orders += 1print(f"Orders filled: {orders}")print(f"Left in stock: {stock}")Orders filled: 3 Left in stock: 2
What this code does
- Each order takes 6 units, and the loop runs only while at least 6 are left.
stockandordersboth change in the body, so the loop ends by itself.- After 3 orders only 2 units are left, which is less than 6.
If you forget countdown -= 1, the loop would print 3 forever until interrupted with Ctrl+C.
Accumulator pattern with while
Accumulator is a variable set before a loop that collects a result round by round, such as a running total or a count. Each round adds something to it.
Use a variable before the loop to accumulate running sums, counts, or products.
total = 0n = 1while n <= 5: total += n n += 1print(f"Sum of 1 to 5: {total}")Example 3 · Savings target
balance = 100monthly_saving = 25months = 0
while balance < 175: balance += monthly_saving months += 1
print(f"Target reached in {months} months")print(f"Final savings: {balance}")Target reached in 3 months Final savings: 175
What this code does
- Increments savings by 25 each month until reaching target of 175.
- Reaches 175 in exactly 3 months.
The accumulator total collects the sum $1 + 2 + 3 + 4 + 5 = 15$.
Next step
Check your understanding
10 quick questions