Repeating with for and range¶
~15 min ยท prerequisite: Repeating with while
What you will be able to do¶
- Write a
forloop that runs its block once for each value produced byrange. - Use
rangewith one, two, or three arguments, and know that the stop value is never included. - Use a loop variable and an accumulator to build a result over many rounds.
The idea¶
A for loop visits the values of a sequence one at a time. For each value, it assigns the value to a loop variable and runs the block. The loop variable is a normal name, and it changes each round. When the sequence has no more values, the loop ends.
The most common sequence for this is produced by range. The function range(5) produces the five values 0, 1, 2, 3, and 4. It starts at 0 and stops before 5, so 5 is never produced. You can give range a start and a stop, as in range(1, 6), which produces 1 through 5. A third argument, the step, sets how much each value changes. The call range(10, 0, -2) produces 10, 8, 6, 4, and 2.
Use for when you know how many rounds you need, and while when you must wait for a condition to change.
An accumulator is a variable that collects a result across rounds. You start it with a value such as 0, and each round you add to it. The variable total in the next example is an accumulator.
Worked example¶
total = 0
for number in range(1, 5):
total += number
print("Added", number, "total is", total)
print("Final", total)
Line by line, this is what Python does:
total = 0stores 0 in the accumulator.range(1, 5)produces 1, 2, 3, and 4. The value 5 is not included.- In the first round,
numberis 1.total += numbermakestotalequal to 1, andprintshows the line. - In the next rounds,
numberbecomes 2, 3, and 4. After each round,totalholds the sum so far. - When there are no values left, the loop ends.
print("Final", total)shows the final sum.
The output is:
Try it¶
Each block checks its result with assert.
The last part of the second block shows that range(5, 5) produces no values, so the block never runs.
Common mistakes¶
-
Expecting
rangeto include the stop value. The following check fails:The loop adds 1, 2, 3, and 4, so the total is 10. To include 5, use
range(1, 6). -
Looping over a plain integer. Writing
for i in 5:gives:A
forloop needs a sequence, such as arange. Writefor i in range(5):instead. -
Giving
rangea float. Writingrange(2.5)gives:The arguments of
rangemust be whole numbers, such asrange(3). -
Using a step of zero. Writing
range(0, 5, 0)gives:A step of zero would never move forward, so Python refuses it. Use a step such as 1 or -1.
Practice¶
- Use a
forloop andrange(1, 11)to add the numbers 1 through 10 tototal. Assert thattotalis 55. - Start with
letters = "". Use aforloop overrange(3)to addstr(i)toletterseach round. Assert thatlettersis"012". - Use
range(0, 21, 5)and a counter to count the values the loop produces. Assert that the count is 5. - Use a
forloop overrange(10, 0, -3)to add each value tototal. Assert thattotalis 22. - Stretch: use a
forloop overrange(2, 21, 2)to add the even numbers from 2 to 20. Assert that the total is 110. Then use awhileloop with a counter that starts at 2 and adds 2 each round until it passes 20, and assert that its total is also 110.
Solution
-
python total = 0 for n in range(1, 11): total += n assert total == 55 -
python letters = "" for i in range(3): letters = letters + str(i) assert letters == "012" -
python count = 0 for value in range(0, 21, 5): count += 1 assert count == 5 -
python total = 0 for value in range(10, 0, -3): total += value assert total == 22
The values are 10, 7, 4, and 1, and their sum is 22.
- ```python total_for = 0 for n in range(2, 21, 2): total_for += n assert total_for == 110
total_while = 0 n = 2 while n <= 20: total_while += n n += 2 assert total_while == 110 ```
Recap¶
- A
forloop runs its block once for each value in a sequence, and assigns each value to the loop variable. range(start, stop, step)produces numbers fromstartup to, but not including,stop.startdefaults to 0 andstepdefaults to 1.- Use
forwhen you know how many rounds you need, andwhilewhen you wait for a condition.