range()
In this tutorial, we'll repeat a known number of times.
range() creates a sequence of numbers for a loop.
for number in range(5):
print(number)
Output:
0
1
2
3
4
Notice that range(5) starts at 0 and stops before 5.
This feels odd at first, but it matches how Python indexes lists and strings. Starting at zero is normal in Python.
Starting and Stopping
You can give range() a start and stop:
for number in range(1, 6):
print(number)
Output:
1
2
3
4
5
The stop number is not included.
Steps
You can also give a step:
for number in range(0, 10, 2):
print(number)
Output:
0
2
4
6
8
The third value tells Python how much to increase each time.
Repeating Code
Use range() when you want to repeat code a known number of times:
for _ in range(3):
print("Hello")
_ is often used when you do not need the loop variable.
Counting Backwards
Use a negative step to count down:
for number in range(5, 0, -1):
print(number)
Output:
5
4
3
2
1
Practice
Use range() to print the numbers from 10 down to 1.