Counting with range
Often you want to repeat something a given number of times, or go through numbers in order. The function range gives the numbers, and for goes through them. With one argument, range(n) gives the numbers from 0 to n - 1:
for i in range(4):
print(i)
0
1
2
3That's 4 numbers, starting from 0: range(4) stops just before 4. So for i in range(4): repeats its block 4 times, which is often all you need.
Start, end and step
With two arguments, range(start, end) starts from start instead of 0. The end is still left out:
for number in range(1, 6):
print(number, "squared is", number * number)
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25To go up to 5, the end must be 6. Forgetting that is the most common range mistake: the loop stops one number too early.
A third argument is the step, how much the number changes each time:
for year in range(2000, 2025, 8):
print(year)
2000
2008
2016
2024The step can also be negative, which counts down. Then the start is the greater number, and the end (left out again) is the smaller one:
for i in range(5, 0, -1):
print(i)
print("Liftoff!")
5
4
3
2
1
Liftoff!Compare this with the while loop that would do the same: a counter, a condition and a -= 1. With range, all three are in one line.
The variable of the loop can be used like any other variable. Here a function uses it to build a line of numbers:
def number_line(n: int) -> str:
line = ""
for i in range(1, n + 1):
line += str(i) + " "
return line
print(number_line(5))
1 2 3 4 5