A range expression creates a sequence of integers for a for loop. With one number, range(N) starts at 0 and stops before N, producing 0 through N − 1. That gives a loop exactly N repetitions. section 16.3
Counting from zero
for v in range(3): print("var v is", v) Python assigns 0, then 1, then 2 to v, executing the indented print statement after each assignment. section 16.3
Customize the sequence with up to three numbers:
- range(end) starts at 0 and uses a step of 1; range(5) produces 0, 1, 2, 3, 4. section 17.1
- range(start, end) begins at start, uses a step of 1, and excludes end; range(2, 6) produces 2, 3, 4, 5. section 17.1
- range(start, end, step) controls the increment; range(2, 9, 2) produces 2, 4, 6, 8. section 17.1
- A negative step counts downward, as in range(6, 2, -1), which produces 6, 5, 4, 3; incompatible directions produce no values. section 17.1
Use range when a loop needs integer values or a fixed number of repetitions. For loops can also iterate directly over other sequences, such as the characters in a string. section 16.4 section 17.3







