for vs while

for vs while

Use for when you know (or can compute) how many times you need to repeat, or you're processing every item in a collection. Use while when you're repeating until some condition changes, and you don't know in advance how many iterations that'll take.

# for: a fixed, known number of repetitions
for i in range(10):
    ...

# while: repeat until a condition becomes false
while balance > 0:
    balance -= monthly_payment

You genuinely don't know ahead of time how many payments it'll take to pay off balance — it depends on the numbers. That's the signature of a while loop.

The infinite loop trap

A while loop's condition has to eventually become false, or it never stops. This is the classic beginner bug:

i = 0
while i < 5:
    print(i)
    # forgot to update i! this loops forever

Every while loop needs something inside it that moves toward making the condition false — usually incrementing/decrementing a counter, or otherwise changing the value being checked.

i = 0
while i < 5:
    print(i)
    i += 1   # this line makes the loop eventually stop

break and continue

break exits a loop immediately, skipping any remaining iterations:

for n in [1, 2, 3, 4, 5]:
    if n == 3:
        break
    print(n)
# 1 2  (stops before printing 3, 4, 5)

continue skips just the rest of the current iteration and moves to the next one:

for n in [1, 2, 3, 4, 5]:
    if n % 2 == 0:
        continue
    print(n)
# 1 3 5  (even numbers are skipped, loop keeps going)

With for, while, the accumulator pattern, and break/continue, you have everything you need to solve the problems in this section.