Conditional sum

The loop in Listing 1 adds each even value of i to total.

Listing 1: Conditional sum using a for loop (Question 1).
total = 0  # Running total for the selected values.

for i in range(1, 5):
    if i % 2 == 0:
        total = total + i

What is total after the loop?

  1. 0
  2. 3
  3. 6
  4. 10
  • range(start, stop, step) supplies integers from start toward, but excluding, stop.
    • step defaults to 1, and range(stop) starts at 0.
    • list(range(2, 7, 2)) is [2, 4, 6]; list(range(5, 1, -2)) is [5, 3].
    • A range is empty when the step cannot reach the stop; a zero step raises ValueError.
  • list collects the supplied values in a new list.