Skip to main content

Section 6.3 For Loop Range

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.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 6.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 6.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.
Trace of the loop (x is 0 to 10)
x increments by 1 But only when the x is evenly divisible by 5 is the value added to total.
Trace of the loop (x is 10 to 35, skipping 5)
Trace of the loop (x is 35 to 45 skipping 5, then 45 to 50)
Answer.
Output is 225
You have attempted of activities on this page.