Section 5.3 For Loop Range
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.3.1
Problem: Given the following code, what is the output?
total = 0
for x in range(5, 50):
if x % 5 == 0:
total += x
print(total)
Subsection 5.3.2 Determine loop components
Starting values: The initial value in x will be 5.
total = 0
Iteration Variable: The iteration variable x will be increased by 5 every iteration.
Termination condition: When x is 50
Body that is repeated based on indentation:
if x % 5 == 0:
total += x
Subsection 5.3.3 Trace the loop, writing updated values for every iteration or until you identify the pattern
For every iteration of loop, write down values.
x
increments by 1
But only when the x
is evenly divisible by 5
is the value added to total
.Answer.
Output is
225
You have attempted of activities on this page.