Counting with range()
The for loop goes through the elements of a list. Very often, though, you just need to count: from 1 to 10, or simply “do this three times”. For that, Python has range(). It gives the for loop whole numbers, one after another:
for i in range(5):
print(i)This prints:
0
1
2
3
4range(5) gives five numbers, from 0 to 4. Like list indexes, it starts at 0, and it stops just before the number you give it: the 5 itself is not included. The loop variable is often called i (for “index”), but any name works.
To start somewhere else, give range() two numbers, the start and the stop:
for number in range(1, 4):
print(number)1
2
3The start is included, the stop is not. To count from 1 to 10, you write range(1, 11). Forgetting this is the most common mistake with range(): range(1, 10) ends at 9.
A third number is the step: how much to add each time. range(0, 21, 5) counts by fives:
for number in range(0, 21, 5):
print(number)0
5
10
15
20A negative step counts down: range(3, 0, -1) gives 3, 2 and 1. The stop, 0, is again not included.
With range(), it's easy to repeat something a given number of times. This loop doesn't use i at all; range(3) only makes it run three times:
for i in range(3):
print("Hip hip hooray!")Hip hip hooray!
Hip hip hooray!
Hip hip hooray!In the first exercise of this lesson, you counted with while: a variable before the loop, a condition, and number += 1 at the end of the block. for number in range(1, 6): does the same in one line. And because range() moves on to the next number by itself, you can't forget to increase a counter and get stuck in an endless loop.
So which loop should you use? for when you know how many times the loop will run: once for each element of a list, or a given number of times with range(). while when you don't know in advance, for example to keep doubling a number until it is greater than 1000:
number = 1
doublings = 0
while number <= 1000:
number = number * 2
doublings += 1
print("Doublings:", doublings)
print("Number:", number)Doublings: 10
Number: 1024Instructions
Rewrite the while loop in the editor as a for loop with range(), and delete the while loop. The program still prints the numbers from 1 to 5.
Change your loop so that it prints the numbers from 1 to 10, including 10.
Below it, write a second loop that prints every fifth number from 0 to 50: 0, 5, 10 and so on up to 50, each on its own line. Use the third number of range(), the step.
Start programming for free
3/11