Python range() Function in a for Loop
Repeat Code n Times with range()
The range() function makes a row of whole numbers for a for loop to go through. range(5) gives 0, 1, 2, 3, 4: five numbers, starting at 0.
for i in range(5):
print(i)0 1 2 3 4
Think of it like the tickets at a counter: the machine hands out ticket 0, then 1, then 2, until it has given out as many as you asked for.
The rules
range(n)givesnnumbers: from0up ton - 1.- The number
nitself is not included.range(5)stops at 4. iis the usual name for a loop variable that only counts.
Repeat something n times
Often you don't even need the number. You only want the block to run a certain number of times:
for i in range(3):
print("Hip hip hooray!")Hip hip hooray! Hip hip hooray! Hip hip hooray!
Change 3 to 10, and the cheer runs 10 times. No copying and pasting.
Why start at 0?
It matches list indexes from chapter 9: the first item is at index 0. You'll see in the last lesson of this topic how that helps. And if you want to start at 1, the next lesson shows you how.
Common beginner doubt: "Does range(3) make a list?" Not quite. It's a range: it hands out its numbers one at a time, when the loop asks for them. For a for loop, it works just like a list of numbers.
range(n) gives n numbers, from 0 up to n - 1.