Skip to main content

Section 5.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 5.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 5.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 5.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.
Total: 13
You have attempted of activities on this page.