Skip to main content

Section 6.9 For Loops with Lists

Subgoals for Evaluating a Loop.

  1. Determine Loop Components
    1. Start condition and values
    2. Iteration variable and/or update condition
    3. Termination/final condition
    4. Body that is repeated based on indentation
  2. Trace the loop, writing updated values for every iteration or until you identify the pattern

Subsection 6.9.1

Problem: Given the following code, what is the output?
mixed_numbers = [5, 3, -4, 7, 2]
total = 0
for number in mixed_numbers:
    total = total + number
print("Total:", total)

Subsection 6.9.2 Determine loop components

Starting values:
total = 0
mixed_numbers = [5, 3, -4, 7, 2]
# The initial value for number will be 5, since that is the first element of the list
Termination condition: When we have finished processing the last element of the list (2)
Body that is repeated based on indentation:
total = total + number

Subsection 6.9.3 Trace the loop, writing updated values for every iteration or until you identify the pattern

For every iteration of loop, write down values.
Trace of the loop for the code in the problem
number total mixed_numbers
5 5 [5, 3, -4, 7, 2]
3 8 [5, 3, -4, 7, 2]
-4 4 [5, 3, -4, 7, 2]
7 11 [5, 3, -4, 7, 2]
2 13 [5, 3, -4, 7, 2]
Total: 13
You have attempted of activities on this page.