Section 5.9 For Loops with Lists
Subgoals for Evaluating a Loop.
-
Determine Loop Components
- Start condition and values
- Iteration variable and/or update condition
- Termination/final condition
- Body that is repeated based on indentation
- 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.