Skip to content

Repeating with for and range

~15 min ยท prerequisite: Repeating with while

What you will be able to do

  • Write a for loop that runs its block once for each value produced by range.
  • Use range with 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:

  1. total = 0 stores 0 in the accumulator.
  2. range(1, 5) produces 1, 2, 3, and 4. The value 5 is not included.
  3. In the first round, number is 1. total += number makes total equal to 1, and print shows the line.
  4. In the next rounds, number becomes 2, 3, and 4. After each round, total holds the sum so far.
  5. When there are no values left, the loop ends. print("Final", total) shows the final sum.

The output is:

Added 1 total is 1
Added 2 total is 3
Added 3 total is 6
Added 4 total is 10
Final 10

Try it

Each block checks its result with assert.

count = 0
for i in range(4):
    count += 1
assert count == 4

total = 0
for i in range(5):
    total += i
assert total == 10

evens = 0
for i in range(0, 10, 2):
    evens += 1
assert evens == 5
result = ""
for i in range(3, 0, -1):
    result = result + str(i)
assert result == "321"

last = -1
for i in range(10, 13):
    last = i
assert last == 12

ran = False
for i in range(5, 5):
    ran = True
assert not ran

The last part of the second block shows that range(5, 5) produces no values, so the block never runs.

Common mistakes

  1. Expecting range to include the stop value. The following check fails:

    values_total = 0
    for i in range(1, 5):
        values_total += i
    assert values_total == 15
    
    AssertionError
    

    The loop adds 1, 2, 3, and 4, so the total is 10. To include 5, use range(1, 6).

  2. Looping over a plain integer. Writing for i in 5: gives:

    TypeError: 'int' object is not iterable
    

    A for loop needs a sequence, such as a range. Write for i in range(5): instead.

  3. Giving range a float. Writing range(2.5) gives:

    TypeError: 'float' object cannot be interpreted as an integer
    

    The arguments of range must be whole numbers, such as range(3).

  4. Using a step of zero. Writing range(0, 5, 0) gives:

    ValueError: range() arg 3 must not be zero
    

    A step of zero would never move forward, so Python refuses it. Use a step such as 1 or -1.

Practice

  1. Use a for loop and range(1, 11) to add the numbers 1 through 10 to total. Assert that total is 55.
  2. Start with letters = "". Use a for loop over range(3) to add str(i) to letters each round. Assert that letters is "012".
  3. Use range(0, 21, 5) and a counter to count the values the loop produces. Assert that the count is 5.
  4. Use a for loop over range(10, 0, -3) to add each value to total. Assert that total is 22.
  5. Stretch: use a for loop over range(2, 21, 2) to add the even numbers from 2 to 20. Assert that the total is 110. Then use a while loop 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
  1. python total = 0 for n in range(1, 11): total += n assert total == 55

  2. python letters = "" for i in range(3): letters = letters + str(i) assert letters == "012"

  3. python count = 0 for value in range(0, 21, 5): count += 1 assert count == 5

  4. 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.

  1. ```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 for loop runs its block once for each value in a sequence, and assigns each value to the loop variable.
  • range(start, stop, step) produces numbers from start up to, but not including, stop. start defaults to 0 and step defaults to 1.
  • Use for when you know how many rounds you need, and while when you wait for a condition.

Sources