Check your understanding of the previous reading: the Count, Sum and Accumulation patterns, and what goes inside the body of a loop.

Question 1

After the third iteration of the loop, what is the value of sum?

sum = 0
values = [4, 2, 6]
for value in values:
    sum = sum + value

Show worked solution

sum starts at 0, and the three iterations add 4, 2 and 6: 0 + 4 = 4, 4 + 2 = 6, 6 + 6 = 12. The answer is 12.

Question 2

What does line 4 do?

count = 0
values = [4,5,6]
for value in values:
    count = count + 1

Select one answer, then check.

  • Correct. The right side is evaluated first, using the old value of count, and the result is then stored back in count.
  • Not quite. = is assignment, not an equation: the right side is computed first, then stored in the variable.
  • Not quite. That would be count = count + value, the Sum pattern. This line adds 1: the Count pattern.
  • Not quite. The list isn't changed; only the count variable is updated.

Question 3

Is the print call before, inside, or after the for loop?

for name in names:
    print(name)

Select one answer, then check.

  • Not quite. Code before the loop would come above the for line.
  • Correct. The print line is indented under the for line, so it is in the body and runs once for each name.
  • Not quite. Code after the loop would be unindented, below the body.

Question 4

What is the value of any after the following Boolean Accumulation is executed?

conditions = [False, False, True, False]
any = False
for condition in conditions:
    any = any or condition
print(any)

Show worked solution

any starts as False and stays False through the first two conditions. The third condition, True, makes any or condition True, and True or False keeps it True. The answer is True.

Question 5

True or false: the following code prints True.

names = ["Alice", "Bob", "Carol"]
joined_names = "Alice, Bob, Carol"
added_names = ""
for name in names:
    added_names = added_names + name + ", "
print(added_names == joined_names)

Select one answer, then check.

  • Not quite. The loop adds ", " after every name, including the last, so added_names ends up as "Alice, Bob, Carol, ", which is not equal to joined_names.
  • Correct. added_names ends up as "Alice, Bob, Carol, ", with a trailing comma and space, so the comparison is False.