for and range()
🌍 In real life. A teacher calls the roll: roll 1, roll 2, roll 3, … up to the last student. The teacher knows exactly how many names there are before starting, and calls each number once.
When you know the values a loop should go through, for is the loop to use.
The idea in one sentence: for takes each value from a sequence, like range(4), puts it in the loop variable, and runs the block once for each value.
Its words:
- loop variable: the name after
for, likei, which holds the current value range(stop): the numbers 0, 1, 2, … up to just beforestoprange(start, stop, step): start somewhere else, and jump bystep; a negative step counts down
Step by step, for for i in range(4)::
range(4)gives 0, 1, 2, 3.igets 0, and the block runs. Thenigets 1, and the block runs again.- The same for 2 and 3.
- No values are left, so the loop ends.
for i in range(4):
print(i)range(start, stop) starts somewhere else, and a third number is the step: range(start, stop, step). A negative step counts down. You don't even have to use the loop variable:
for n in range(1, 4):
print(n, "squared is", n * n)
for i in range(3):
print("Hip hip hooray!")for n in range(10, 0, -3):
print(n)Why the stop is left out. As with slices, it keeps the counting tidy: range(n) gives exactly n values, and range(a, b) gives b - a values. range(4) is "4 laps".
What it costs. range doesn't build a list of numbers first; it hands them out one at a time. So range(1000000) takes almost no memory. The loop still does one lap per number, so a million numbers means a million laps.
for or while? Use for when you know the values (a range, a word, a list). Use while when you only know when to stop.
The same loop can work with numbers you read from the user:
n = int(input("Table of: "))
for i in range(1, 4):
print(f"{n} x {i} = {n * i}")Mistakes and edge cases.
- Expecting the stop number.
range(1, 10)ends at 9. Writerange(1, 11)to include 10. - Counting down without a negative step.
range(5, 1)is empty, so the loop never runs. Writerange(5, 1, -1). - A decimal step.
range(0, 1, 0.5)givesTypeError: 'float' object cannot be interpreted as an integer. - Looping over a number.
for i in 5:givesTypeError: 'int' object is not iterable. Writerange(5). - Changing the loop variable. Setting
i = 10inside the block doesn't skip ahead: on the next lap,forgivesithe next value anyway.
Quiz
What does this print?
for i in range(2, 5): print(i)How many numbers does
range(1, 10)give?- 9
- 10
- 11
What does this print?
for i in range(0, 10, 4): print(i)What does this print?
total = 0 for i in range(1, 4): total += i print(total)Which line has a mistake?
for i in range(3): print(i)
Coding tasks
Print the even numbers from 2 to 20, one per line. Use
range()with a step.Ask for a whole number
n. Print its times table from 1 to 5, in this form:3 x 1 = 3 3 x 2 = 6Ask for a whole number
n. Print a triangle of stars: 1 star on the first line, 2 on the second, up ton.