Loops: while & for
Computers are extraordinarily good at doing the same thing a thousand times without complaining. This chapter teaches you how to ask for that.
1. while loops
A while loop repeats its block as long as a condition
stays True. Every while loop needs three
things: a starting point, a condition, and something that eventually
makes the condition false — skip that last part and your loop
never stops.
minutes_to_open = 5 # starting point
while minutes_to_open > 0: # condition
print("Opening in", minutes_to_open, "minute(s)...")
minutes_to_open -= 1 # the step that eventually stops the loop
print("We're open!")
False, so it runs forever (or until you force-stop the
program). This almost always happens by forgetting the step that
changes the loop variable — if you removed
minutes_to_open -= 1 above, minutes_to_open
would stay 5 forever and the café would never open.
A countdown always ends the same way, so it's a safe first example.
Real registers need a while loop for something riskier:
letting someone retry a few times, then locking them out.
manager_pin = "4471"
attempts = 0
entered = ""
while attempts < 3 and entered != manager_pin:
entered = input("Enter manager PIN: ")
attempts += 1
if entered != manager_pin:
print("Incorrect PIN. Try again.")
if entered == manager_pin:
print("Register unlocked.")
else:
print("Too many failed attempts. Register locked.")
Enter manager PIN: 1111
Incorrect PIN. Try again.
Enter manager PIN: 9999
Incorrect PIN. Try again.
Enter manager PIN: 4471
Register unlocked.
Notice the condition has two parts joined by and:
attempts < 3 caps how many tries are allowed, and
entered != manager_pin stops the loop the moment the
correct PIN shows up. Either one becoming false ends the loop —
that's what makes a "retry, but not forever" loop possible.
Go Deeper: the three parts of every loop, named properly
Every loop — while or for — has
three conceptual parts: initialization (where the
loop starts), the condition (how many times it
runs), and the step (increment or decrement).
Getting any one of these wrong is the source of almost every loop
bug you'll ever write — when a loop misbehaves, check these
three things first, in this order.
while condition:repeats its block as long as the condition isTrue.- Every loop needs initialization, a condition, and a step that eventually stops it.
- Forgetting the step creates an infinite loop.
- Combining conditions with
and/orlets awhileloop stop for more than one reason — like "correct PIN" or "too many attempts."
2. for loops and range()
When you already know how many times you want to repeat something,
a for loop combined with range() is more
direct than managing a counter variable yourself.
for i in range(5):
print(i) # prints 0, 1, 2, 3, 4 (5 is NOT included)
for i in range(1, 6):
print(i) # prints 1, 2, 3, 4, 5
for i in range(10, 0, -2):
print(i) # prints 10, 8, 6, 4, 2 (counting down by 2)
range(stop) counts from 0 up to (but not including)
stop. range(start, stop) counts from
start up to (not including) stop.
range(start, stop, step) adds a step size, which can be
negative to count backward. The end value is always
excluded — this trips up almost every beginner at least
once.
Corner Café puts this to work the moment the lunch rush hits: every walk-in order needs its own numbered ticket, printed in one batch.
# Corner Café is slammed during the lunch rush — print a numbered
# ticket for every walk-in order waiting in line.
first_ticket = 1001
order_count = 5
for ticket in range(first_ticket, first_ticket + order_count):
print("Printing order ticket #" + str(ticket))
Printing order ticket #1001
Printing order ticket #1002
Printing order ticket #1003
Printing order ticket #1004
Printing order ticket #1005
range(first_ticket, first_ticket + order_count) is the
same two-argument form from the first example — only the start
and stop are now expressions instead of literal numbers, so the
ticket range shifts automatically if the shop changes its starting
ticket number tomorrow.
Go Deeper: for loops work on more than just range()
for can iterate directly over any sequence — a
string, a list, later a dictionary. for letter in "abc":
runs the block once per character, no range() or index
needed at all. You'll use this constantly starting in Chapter 6.
for i in range(n):counts0ton-1.range(start, stop, step)gives full control, and the stop value is always excluded.range()'s arguments can be expressions, not just literal numbers — handy for things like a shifting ticket range.forcan iterate directly over strings and other sequences, not just numbers.
3. Common loop patterns
A handful of loop "shapes" show up constantly in real code and in interviews. Learning to recognize them is more valuable than memorizing any single example.
0) that
collects a running result across every loop iteration — a sum, a
count, a product. It's called an accumulator because it "accumulates"
the answer one step at a time instead of computing it all at once.
At closing time, the shift lead types in that hour's sales one number at a time, and the register keeps a running total — the accumulator pattern, driven by real input.
# The "accumulator" pattern: build up a result across iterations
hours_worked = 5
total_sales = 0
for hour in range(hours_worked):
sale = float(input("Enter sales for hour " + str(hour + 1) + ": $"))
total_sales += sale
print("Total sales for the shift: $" + str(total_sales))
Enter sales for hour 1: $120.50
Enter sales for hour 2: $95
Enter sales for hour 3: $60.25
Enter sales for hour 4: $200
Enter sales for hour 5: $80
Total sales for the shift: $555.75
total_sales never sees all five numbers at once —
it just adds whatever input() hands it, one hour at a
time, which is exactly why an accumulator works even when the data
arrives gradually instead of all up front.
Every receipt Corner Café prints also carries a check digit —
the sum of all its digits — so a cashier can spot a mistyped
receipt number at a glance. Computing it needs a second pattern:
peeling a number apart one digit at a time with % and
//.
# Digit-by-digit processing: peel off digits with % and //
receipt_number = 40352
digit_sum = 0
n = receipt_number
while n > 0:
digit_sum += n % 10 # grab the last digit
n = n // 10 # drop the last digit
print("Digit sum of receipt", receipt_number, ":", digit_sum)
check_digit = digit_sum % 10
print("Expected check digit:", check_digit)
It's easier to trust this loop once you've watched
n and digit_sum change, step by step,
instead of just reading the final printed number:
n n % 10 digit_sum n // 10
40352 2 2 4035
4035 5 7 403
403 3 10 40
40 0 10 4
4 4 14 0
Each row is one pass through the loop: n % 10 peels off
the last digit, that digit is folded into digit_sum,
and n // 10 drops it before the next pass. Once
n reaches 0, every digit has been counted
and the loop stops on its own.
Go Deeper: peeling off digits with % and //
n % 10 always gives you the last digit of n
(in base 10). n // 10 removes that last digit by
floor-dividing it away. Repeating both together in a loop lets you
process a number digit by digit — this exact pattern solves
digit-sum, digit-reversal, and palindrome-checking problems, all
common interview questions.
- The accumulator pattern: a variable that builds up a result across iterations, even when the data arrives one
input()at a time. n % 10gets the last digit;n // 10removes it.- Tracing a loop's variables row by row makes it obvious why it stops when it does.
4. break & continue
Sometimes you need to exit a loop early, or skip just one iteration
without stopping the whole thing. break and
continue handle exactly those two cases.
# break: stop the loop immediately once we find the target ticket
target_ticket = 1004
for ticket in range(1001, 1006):
if ticket == target_ticket:
print("Found it:", ticket)
break
print("Checking ticket", ticket)
# continue: skip just this ticket, keep looping
for ticket in range(1, 6):
if ticket == 3:
continue
print(ticket) # prints 1, 2, 4, 5 (3 is skipped)
break exits the loop completely — nothing after it
in the loop runs again. continue jumps straight back to
the loop's condition, skipping the rest of the current iteration's
code but continuing to loop.
Corner Café's order queue needs both at once: a bad entry
($0, an empty order) should just be skipped with
continue, while a cancel signal (a negative amount)
should shut the whole queue down early with break.
# Process up to 5 orders; a negative amount is a "cancel" sentinel
# that should stop the queue completely.
total_orders = 0
total_revenue = 0.0
for order_number in range(1, 6):
amount = float(input("Order " + str(order_number) + " amount: $"))
if amount < 0:
print("Cancel signal received -- closing the queue early.")
break
if amount == 0:
print("Skipping an empty order.")
continue
total_orders += 1
total_revenue += amount
print("Processed order", order_number, "for $" + str(amount))
print("Orders processed:", total_orders)
print("Total revenue: $" + str(total_revenue))
Order 1 amount: $12.50
Processed order 1 for $12.5
Order 2 amount: $0
Skipping an empty order.
Order 3 amount: $8
Processed order 3 for $8.0
Order 4 amount: $-1
Cancel signal received -- closing the queue early.
Orders processed: 2
Total revenue: $20.5
The loop never even asked for a 5th order — break
exited on the spot once it saw -1. Compare that to
order 2: continue skipped the totals for that one
order, but the loop kept going and still asked for order 3
afterward.
breakexits the loop entirely.continueskips only the current iteration, then keeps looping.- A sentinel value (like a negative amount meaning "cancel") is a common real-world reason to
breakout of a loop early.
- Every "processing 10,000 rows" data pipeline, every web crawler, every batch email sender is fundamentally a loop over a collection — the accumulator pattern you learned here shows up in almost all of them.
- An infinite loop in production doesn't just "run forever" politely — it's one of the most common causes of a server hanging and an on-call engineer getting paged at 3am.
- The digit-peeling pattern (
%///) is a genuinely common warm-up question at technical interviews, precisely because it tests whether you understand these two operators deeply, not just loop syntax.
Points to Remember
while condition:repeats until the condition is false; always ensure it eventually becomes false.for i in range(...):is ideal when you know the number of repetitions in advance; the stop value is always excluded.- The accumulator pattern builds up a result (sum, count) across iterations.
n % 10/n // 10peel digits off a number one at a time.breakexits a loop early;continueskips just the current iteration.