COGNITION FOUNDRYLEARN. BUILD. UNDERSTAND.
PY-009 / Repeat with intention◷ 18 min read + practice

For loops and range

A loop runs a block once for each value in a sequence. Instead of copying a print statement five times, we can describe what changes from one repetition to the next.

By the end, you can: Write a for loop, reason about range() start, stop and step values, and build a running total.
Before this lesson: PY-008

A for loop visits values

for item in ...: gives a name to each successive value. The indented loop body runs once for each one. After the last value the program continues below the loop.

A string is iterable: visiting "cat" yields "c", then "a", then "t". Later we will work with lists and dictionaries as well.

The stop argument is excluded

range(4) produces 0, 1, 2 and 3. range(2, 6) produces 2, 3, 4 and 5. Python does not include the stop value, which is the source of many beginner off-by-one mistakes.

range(start, stop, step) can count in different increments, including backwards with a negative step. A zero step is invalid and raises ValueError.

Carry a result between iterations

An accumulator is a variable that stores a result as the loop progresses. Start with total = 0, then update it using total += amount during each iteration.

Place the final print *after* the loop if you want a single total. Printing within the loop instead gives a running commentary. Both are useful once you know which you intended.

Choose readable names and safe sizes

Choose a loop variable that explains what is being visited, such as letter, number or price. A loop over a million values is possible, but a short example is easier to inspect.

The browser editor has a runtime timeout to limit runaway code. Learn to reason about the amount of work before choosing a large range.

Try it yourself.

Choose a starting example or write something completely different. You control the code; the Run button executes what is in the editor, not a hidden preset.

CF Python PlaygroundBrowser-based Python
Ready to load Python
Count with range

Print the integers 1 through 4 using an exclusive stop.

Syntax colours highlight Python code. Tab inserts four spaces; press Escape then Tab to leave the editor. Ctrl+Enter runs the current code.
OUTPUT / ERRORS
Press Run Python to execute the editable code.
NOW MAKE IT YOURS

Change the range so the final step is 6.

Need a hint?

The stop must be one more than the final number.

On first Run, a pinned Python runtime downloads from jsDelivr. Code executes locally in your browser's Web Worker, not on our server. It cannot inspect your normal PC files or Windows hardware. Avoid entering secrets. Heavy/infinite loops are stopped by a time limit.

Check your understanding.

Try answering each question before opening its reference answer. Explain the idea aloud or change an example to test it for yourself.

  1. Why does range(2, 6) produce four numbers instead of five?

    View answer

    The range(start, stop) interval includes start but excludes stop. So range(2, 6) gives the four values 2, 3, 4 and 5. This half-open interval is useful for many indexing operations, but you must remember the excluded boundary when counting inclusive values.

  2. Where would you put print(total) to display only the final accumulated sum?

    View answer

    Put print(total) after the loop body at the same indentation level as for, not inside its indented block. The variable total is updated for every iteration and then printed once. If the print is indented inside the loop, you will see the intermediate running totals instead.

Where this leads.

For loops work well when values or a range are already known. While loops express repetition controlled by a changing condition.