Loops and repetition.
Repeat a step with a clear stopping rule and a clear record of progress.
Start here.
A loop repeats a block of instructions. A list, written with square brackets, holds an ordered sequence of values such as [8, 12, 5]. A for loop takes each value from the sequence in turn: for price in prices: means 'for each value in prices, call that value price while this body runs'. The colon introduces the indented body. After the final item, the loop ends and execution continues with the next unindented line.
A running total begins with a known value, usually zero for addition. The expression total += price is shorthand for total = total + price. Each pass reads the old total and the current price, adds them, and assigns the new total back to the same name. The loop's meaning is that total always holds the sum of items already visited. When the sequence is empty, the body runs zero times and total stays zero.
A while loop repeats while a condition is True, so its body must usually change something that eventually makes the condition False. range(5) supplies the numbers 0 through 4 for five passes; Python stops before the endpoint. Use for when values come from a known sequence, and while when you are waiting for a changing condition. In either case, find the start, what changes once per pass, and why the repetition ends.
Build the model.
Automation often means applying one small rule to many items. A for loop takes each value from an iterable, such as a list, string, range, or file, and runs a body for it. A while loop repeats while a condition remains true. Choose for when you already have a sequence; choose while when the stopping point depends on changing state.
The most important question about a loop is what changes each time. For a running total, the total should represent everything visited so far. For a search, the current position or remaining candidates should move toward an ending. Trace a short example by hand before running it; the first pass, last pass, and empty input reveal many mistakes.
How it works.
range(5) produces 0 through 4, not 1 through 5. This half-open convention makes a count of five iterations easy, but it also causes off-by-one errors when a human describes an inclusive endpoint. In for item in items, item is the current value; use enumerate(items) when you also need its index.
break exits the nearest loop early. continue skips the rest of the current pass and moves to the next one. Both can clarify a loop when used sparingly, but too many exits make its behavior hard to trace. A while loop must update the state used by its condition or it may never stop.
Read it line by line.
prices = [8, 12, 5]
total = 0
for price in prices:
total += price
print(total)total starts at 0. The loop binds price to 8 and changes total to 8; then 12 changes it to 20; then 5 changes it to 25. The list has no more values, so the loop ends and print writes 25. An empty list would skip the body and print 0, which is a useful identity for addition.
See the rule again.
measurements = [18, 24, 21, 19]
count = 0
for value in measurements:
if value > 20:
count += 1
print(count)The output is 2. Only 24 and 21 pass the strict comparison. count starts at zero and increases once per qualifying item; it does not depend on the position of those items.
A mistake to avoid.
If a list must be changed while you iterate, consider building a new list. Removing elements from the original can shift positions and cause the loop to skip work.