~/learn/Python · Fundamentals
Repeating work with loops
Walk through values, use range and build a running total one step at a time.
why this matters
A loop turns a calculation for one item into a calculation for a whole dataset, without copying instructions repeatedly.
A loop repeats instructions. A for loop takes one value at a time from a sequence. A list, written with square brackets, is one way to store several values in order. In for price in prices, price is the current value, not its position. The indented block runs once for each value.
Try it: Add 4 to the end of prices. How many times does print(price) run?
A running total is also called an accumulator: a variable that collects results over time. Start it before the loop. Each step adds the current value to the previous total. total += price is shorthand for total = total + price.
Try it: Add a price of 4. The final total should become 14.
Trace each step
Before loop: total = 0 price = 3 → total = 0 + 3 = 3 price = 5 → total = 3 + 5 = 8 price = 2 → total = 8 + 2 = 10
range(stop) produces whole numbers from 0 up to, but not including, stop. range(1, 4) produces 1, 2, 3. Add a third argument for the step size: range(2, 7, 2) produces 2, 4, 6. Use range when you need a sequence of counts, rather than items from an existing list.
Try it: Print the numbers 1 through 5, including 5.
A while loop repeats for as long as its condition is true. Unlike for, it does not automatically move through a sequence. You must change something so that the condition eventually becomes false.
Try it: Start remaining at 2. Trace how it reaches 0.
Avoid two loop traps
Resetting total = 0 inside the loop erases earlier work. Forgetting to update a while condition can make it run forever. Start with small, finite inputs and trace each step before using a larger input.
An empty list makes a for loop run zero times, so a correctly initialised total stays 0. The next Collections chapter explains lists in more depth, including positions, adding items and selecting part of a list.
key takeaways
- for visits each item; an empty list gives zero iterations.
- Initialise a running total before the loop.
- range excludes its stop value.
- A while loop must make progress toward a false condition.
check your understanding
total = 0 for number in range(1, 4): total += number What is total?
free practice
Build confidence with a question you can solve without Pro.