Decisions and loops
Repeat with for and range
Repeat a block a known number of times and calculate a running total.
Lesson 15 of 63
Reading: about 2 min
Lesson + practice: about 12 min
Difficulty: Beginner
On this page4 sections
A for loop repeats its indented block for each value from an iterable. range(1, 4) produces 1, 2, and 3: the stop value is excluded.
for day in range(1, 4):
print(f"Day {day}")Day 1 Day 2 Day 3
Keep a running total
Create the total before the loop. Then add each value while the loop runs. The += operator is shorthand for assigning total + value back to total.
total = 0
for day in range(1, 4):
total += day * 10
print(total)60
Why this works
range(start, stop) generates a sequence of integers up to, but not including, stop. The loop variable receives one value at a time, then the indented body runs. A running total must be created before the loop; otherwise it would not preserve the sum of earlier iterations.
Practice
Use range(1, 6) to print days 1 through 5. Then add 15 minutes for each day to a running total and print 75.
Does range(1, 4) include 4?
Reveal answer
No. It produces 1, 2, and 3; the stop value is excluded.
Try another case
How many times does for day in range(2, 6) run, and which values appear?
Check your answer
Reveal answer
Four times, with day equal to 2, 3, 4, and 5.
Your progress
Reveal the check answer or reach the end to complete this lesson.