Check your understanding of the previous reading: the parts of a for loop, the iteration variable, and how a loop runs.

Question 1

Identify each of the components of the for loop:

Two lines of code under `grades = [..., 50, 80]`: `for item in grades:` and an indented `print(item)`, with six numbered labels: 1 points at `for`, 2 at `item`, 3 at `in`, 4 at the indented line, 5 at the end of `grades:`, and 6 at `item` inside `print(item)`.

LabelPoints atComponent
1 for
2 item
3 in
4 print(item)
5 grades:
6 item inside print(item)

Question 2

Type the character used at the end of the first line of a for loop.

Show worked solution

The first line of a for loop ends with a colon, as in for item in grades:. The answer is :.

Question 3

What is the type of the Iteration Variable in this code?

groceries = ["Apples", "Cookies", "Steaks"]
for grocery in groceries:
    print(grocery)

Select one answer, then check.

  • Not quite. groceries is the list; the iteration variable grocery holds one element of it at a time.
  • Correct. Each element of groceries is a string, and the iteration variable takes on one element at a time, so grocery is a string.
  • Not quite. There are no numbers in the list; its elements are strings like "Apples".
  • Not quite. On every pass the iteration variable holds a real value from the list: one of the strings.

Question 4

Mark each of the following statements about for loops that are true:

Select every answer that applies, then check.

  • Not true. The body can hold any number of statements; the whole body runs once for each element.
  • Not true. A function packages code that you call by name; a for loop repeats its body once for each element of a list.
  • True. Each time the loop executes, the iteration variable gets set to the next value from the list.
  • Not true. The body runs once for each element, however many elements the list has.
  • True. After the last line of the body, execution jumps back up to the for line for the next element.

Question 5

Trace the values of this code. If a variable is not yet defined, put an "X" (without quotes).

grades = [10, 20]
total = 0
for grade in grades:
    adjusted = grade + 10
    total = total + adjusted

Each row is one step: the line that just ran, and the value of every variable after it.

steplinegradesgradeadjustedtotal
1 1 [10, 20] X X X
2 2 [10, 20] X
3 3 [10, 20] X
4 4 [10, 20] 20
5 [10, 20]
6
7 [10, 20]
8 [10, 20] 50