Repeat with for and range

Lesson 28 of 54 · Python Foundations

A loop runs a block repeatedly. A for loop takes each value from an iterable—an object capable of providing values one at a time—and binds it to a loop variable. Each pass through the block is an iteration.

for shelf in range(1, 4):
    print("Shelf", shelf)
print("Finished")
Shelf 1
Shelf 2
Shelf 3
Finished

range(1, 4) supplies 1, 2, and 3. The start is included; the stop is excluded. The indented print runs once per value, and the unindented print runs after the loop. The colon and consistent indentation are required; use four spaces per level.

next value → bind shelf → run body → next value
                                  ↘ none left → continue after loop

range(4) starts at zero and supplies 0 through 3. An empty range runs the body zero times. A for loop can also visit other iterables; for example, for letter in "cat": visits each character in order. The loop variable receives values from the iterable; the loop does not automatically change the iterable.

Chapter index