For loops and range
Process each item in a sequence and build useful totals without duplicating instructions.
By the end, you’ll be able to…
- Trace the loop variable and body for each item.
- Use range and enumerate with correct boundaries.
- Accumulate a result and iterate through dictionary items.
01Describe one item of work
A for loop repeats a body once for each item provided by an iterable. Lists, tuples, strings, and dictionaries are iterable objects you already know. In for topic in topics, Python binds topic to the first item, executes the body, then binds it to the next item and repeats. The loop finishes when no items remain. You do not need to update an index manually.
The body is an indented block following a colon. Instructions at the same outer indentation after the loop run once after repetition ends. Trace the loop by making one row per item and writing the current loop variable beside it. If the iterable is empty, the body executes zero times. That empty case should be part of your reasoning, especially when calculating results.
02Use range for an integer progression
range describes a sequence of integers using a start, an excluded stop, and a step. range(4) gives 0, 1, 2, and 3. range(2, 8, 2) gives 2, 4, and 6. A negative step can count downward, but start and stop must face the appropriate direction; range(5, 0, -1) visits 5 through 1. A zero step is invalid.
A range is a compact sequence object rather than a list containing all its numbers. Convert a small range to a list when you want to inspect its values. Choose range when the numbers themselves are part of the task or you need a fixed number of repetitions. For existing list items, direct iteration is usually clearer than combining range with len and repeated indexing.
03Accumulate a result across iterations
An accumulator retains a partial result between iterations. Initialize it before the loop, update it inside the loop, and use the completed result afterward. For a sum, start at zero because adding zero changes nothing. If you place total = 0 inside the loop, every iteration discards the earlier work and only the final contribution remains.
The += operator adds a value and assigns the result back for this integer example. Combine a condition with the loop when only some items should contribute. Predict the accumulator after each item, not just at the end. Once you understand the pattern, built-ins such as sum can express simple totals concisely, but a manual loop remains useful for custom rules and for learning how state changes.
04Keep positions and pairs readable
enumerate supplies a count alongside each item, starting from zero unless you request another start. Use enumerate(topics, start=1) for a human-readable numbered list without changing the list's actual indices. The two names in the loop header unpack each count-item pair. For dictionaries, items supplies key-value pairs, allowing both pieces to receive meaningful names.
Avoid changing a collection's size while iterating over that same collection. Removing list items can skip later elements, and changing dictionary size can raise an error. Build a new collection or iterate over an appropriate copy instead. When loops become nested, describe what one outer iteration means and what one inner iteration means; the inner loop normally completes its entire sequence for each outer item.
The ideas worth keeping.
- A for loop describes the work for each provided item.
- range excludes its stop; enumerate combines a counter with existing items.
- Initialize accumulators before repetition and avoid resizing the collection being visited.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Total qualifying orders
Given orders = [120, 40, 80, 200], calculate the total of orders worth at least 80 using a loop and a condition. Print the total only once after the loop.
Explore a worked solution
orders = [120, 40, 80, 200]total = 0for amount in orders: if amount >= 80: total += amountprint(total)The accumulator receives 120, 80, and 200, producing 400. Initialization outside the loop preserves previous contributions and includes the boundary value 80.
Create a numbered countdown plan
Print a numbered list for topics ['Read', 'Code', 'Review'] beginning at 1. Then use range to print 3, 2, and 1 on separate lines.
Explore a worked solution
topics = ["Read", "Code", "Review"]for number, topic in enumerate(topics, start=1): print(f"{number}. {topic}")for remaining in range(3, 0, -1): print(remaining)enumerate provides display numbers alongside values. The countdown excludes the stop of zero, so it prints exactly the three requested positive integers.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Total qualifying orders
Given orders = [120, 40, 80, 200], calculate the total of orders worth at least 80 using a loop and a condition. Print the total only once after the loop.
0
Keep exploring.
The official references behind this chapter, when you want a second angle or the full details.
One chapter closer.
Reading is a start. Trying it yourself makes the connection.