VMware ESXi and vSphere Cluster Management
Using Python for Loops with range()
Learn how Python for loops use range() to repeat actions with start, stop, and step values, including counting, skipping, and counting backward.
A Python for loop is a control-flow construct that runs its body once for each value in an iterable sequence. An iteration is one execution of the loop body. The built-in range() function is useful when you want to repeat an action a known number of times or generate a sequence of integer values.
This lesson assumes that you can run Python code, use variables and integers, write indented code blocks, and call print().
How range() works in a for loop
range() represents a sequence of evenly spaced integers. A for loop takes one value from that sequence at a time and assigns it to the loop variable. The loop then runs its indented body before moving to the next value.
for number in range(3):
print(number)
The generated values are 0, 1, and 2. Therefore, the loop body runs three times:
0
1
2
Here, number is the loop variable. It receives a different integer during each iteration. The name i is a common convention for a simple index, but any valid and descriptive identifier can be used.
Counted loops versus collection loops
A loop using range() is a counted loop: the generated numbers control how many times the body runs. You can also loop directly over items in a collection, such as a list or string.
for item in ["red", "green", "blue"]:
print(item)
This second loop visits the collection's actual items. In contrast, range() supplies integer positions or counts, which is useful when the action must happen a particular number of times.
range() syntax
The general form is:
range(start, stop, step)
- start is the first value and is included when it is supplied.
- stop is the boundary where the range ends. It is an exclusive endpoint, so it is not included.
- step is the increment or decrement between consecutive values.
The shorter forms use default arguments. A default argument is a value Python uses when an optional argument is omitted.
range(stop)uses a start of0and a step of1.range(start, stop)uses a step of1.range(start, stop, step)specifies all three values.
All range() arguments must be integers or integer-compatible values. An integer is a whole number, such as -2, 0, or 10. The step cannot be zero.
Start and stop boundaries
For an upward range with a positive step, the start value is included and the stop value is excluded. For example:
for value in range(1, 5):
print(value)
The values are 1, 2, 3, and 4. The loop has four iterations; 5 is only the stopping boundary and is not generated.
When counting upward by one, choose a stop value one greater than the desired final value:
for value in range(1, 11):
print(value)
This prints 1 through 10. The output ends at 10 because 11 is excluded.
The default start of 0 matches Python's common zero-based indexing convention. For example, the first item in a list has index 0, the second has index 1, and so on.
range() argument forms
| Expression | Start value | Stop boundary | Step | Generated values |
|---|---|---|---|---|
range(5) | 0 | 5, excluded | 1 | 0, 1, 2, 3, 4 |
range(1, 5) | 1 | 5, excluded | 1 | 1, 2, 3, 4 |
range(1, 10, 2) | 1 | 10, excluded | 2 | 1, 3, 5, 7, 9 |
range(5, 0, -1) | 5 | 0, excluded | -1 | 5, 4, 3, 2, 1 |
Using the loop variable
The loop variable can be included in formatted output or used in a calculation. In this example, an f-string inserts the current value into the message:
for i in range(1, 11):
print(f"This is iteration {i}.")
The first iteration assigns 1 to i, the next assigns 2, and the final iteration assigns 10. The body executes once for every generated value.
You can also calculate with the current value:
for number in range(1, 6):
square = number * number
print(f"{number} squared is {square}")
Repeating an action ten times
Use range(1, 11) when the displayed counter should be numbered for people from 1 through 10:
for i in range(1, 11):
print(f"This is iteration {i}.")
Use range(10) when you only need ten iterations and the zero-based values are useful or do not need to be displayed as human-facing numbers:
for i in range(10):
print(i)
This produces values from 0 through 9. Both loops run ten times. The clearer form depends on the purpose: use range(1, 11) for labels numbered 1 through 10, and range(10) for zero-based counting or a simple repetition count.
Step values
The step controls the distance between values. With the default step of 1, every consecutive integer is generated. A larger positive step skips values:
for i in range(1, 11, 2):
print(f"Odd number: {i}")
The values are 1, 3, 5, 7, and 9. The loop adds 2 after each iteration. Although the stop value is 11, it is excluded; 9 is the final generated value.
A negative step counts downward. For a descending range, the start must be larger than the stop, and the step must be negative:
for seconds in range(5, 0, -1):
print(seconds)
print("Go!")
This generates 5, 4, 3, 2, and 1. The boundary 0 is excluded, so the loop ends before printing it.
A step of 0 is invalid because it would never move toward the stop boundary. Use a nonzero positive or negative integer.
Reading and predicting loop output
To predict a loop, write down the first value, repeatedly apply the step, and stop before including the boundary.
range(4)produces0, 1, 2, 3, so the body runs four times.range(2, 8, 2)produces2, 4, 6;8is excluded.range(10, 4, -2)produces10, 8, 6;4is excluded.
Each value corresponds to exactly one pass through the loop body. For range(1, 11), the values are 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10. That is why an upward range ending at 11 can display values ending at 10.
Common boundary outcomes
| Desired result | Recommended range expression | Reason |
|---|---|---|
| Run exactly 10 times | range(10) | The default sequence contains ten values: 0 through 9. |
| Display 1 through 10 | range(1, 11) | Start at 1 and use a stop boundary one greater than 10. |
| Display even values from 2 through 10 | range(2, 11, 2) | Start at 2, add 2 each time, and exclude 11. |
| Count down from 10 to 1 | range(10, 0, -1) | Use a negative step and exclude the lower boundary 0. |
Troubleshooting range() loops
The expected final number does not appear
range(1, 10) produces values from 1 through 9, not 10. The stop value is exclusive. Use range(1, 11) when the desired final upward value is 10.
The loop starts at 0 instead of 1
The one-argument form, range(10), uses the default start value 0. For labels numbered 1 through 10, use range(1, 11).
A countdown produces no output
An upward step cannot move from a larger start toward a smaller stop. For example, range(10, 0) has no values because its default step is positive. Use range(10, 0, -1).
Python raises an error
Check that every argument is an integer-compatible value and that the step is not zero. Values such as range(1, 5, 0) are invalid. Replace them with a valid nonzero positive or negative step.
The loop runs an unexpected number of times
Trace the generated values before checking the loop body. Verify the start value, the exclusive stop boundary, and the step size. Adjust the stop or step to produce the intended sequence.
Exam-relevant points
range(stop)starts at0and uses a step of1.- The start is included, but the stop is excluded.
- For upward counting to a final value of
n, the usual expression isrange(start, n + 1). - A negative step is required for descending ranges.
- The step cannot be zero.
- The loop variable receives each generated value in sequence.
range(10)andrange(1, 11)both perform ten iterations, but they provide different counter values.