Repeating With for Loops
Use for loops and range() to repeat code a set number of times, count and total values with accumulators, and avoid the off-by-one trap.
Welcome back!
Step 1 of 12Learn
Stop copying and pasting
Suppose you want to print a 10-second countdown. You could write ten print lines. For 100 seconds, you'd need 100 lines, and if you wanted to change the message you'd edit all of them. A loop repeats code for you:
for i in range(5):
print("Push-up number", i)This prints five lines, numbered 0, 1, 2, 3, 4. Here's how it works:
range(5)produces the numbers 0 up to, but not including, 5.- On each pass (called an iteration), the loop variable
itakes the next number. - The indented block runs once per number.
The colon and indentation work just like in an if statement. Lines after the loop, back at the left edge, run once the loop has finished.
You can name the loop variable anything. i is traditional for a simple counter, but a name like lap or level makes the code easier to read when the number means something.
Step 2 of 12Tap to reveal
Three ways to use range()
range(stop)
range(4)gives 0, 1, 2, 3. It starts at 0 and stops before the number you give it, so it produces exactly 4 numbers.range(start, stop)
range(1, 6)gives 1, 2, 3, 4, 5. The start is included and the stop is excluded. To count 1 to 10, writerange(1, 11).range(start, stop, step)
range(0, 20, 5)gives 0, 5, 10, 15. The step is how much to add each time. A negative step counts down:range(10, 0, -2)gives 10, 8, 6, 4, 2.
Step 3 of 12Practice · Choose one
Which loop prints the numbers 1 to 10, including 10?
Step 4 of 12Learn
Accumulators: running totals
Loops become powerful when they build up a result. An accumulator is a variable you create before the loop and update inside it:
total = 0
for day in range(1, 8):
steps = int(input(f"Steps on day {day}: "))
total = total + steps
print(f"Weekly total: {total}")
print(f"Daily average: {total / 7:.0f}")The pattern is always the same: start the accumulator (often at 0), update it on every iteration, use it after the loop.
A frequent bug is putting total = 0 inside the loop. Then it resets on every pass, and at the end you only have the last day's steps.
Counting is the same pattern, adding 1 instead of a value:
evens = 0
for n in range(1, 21):
if n % 2 == 0:
evens += 1
print(evens) # 10Notice the if block is indented twice: once for being inside the loop, and once more for being inside the if.
Step 5 of 12Practice · Chart
An accumulator over one week of steps
On which day does the running total first go above 30,000?
Tap the point that answers the question, then press Check.
| Item | Running total | Steps that day |
|---|---|---|
| Day 1 | 5,200 | 5,200 |
| Day 2 | 11,300 | 6,100 |
| Day 3 | 16,100 | 4,800 |
| Day 4 | 23,400 | 7,300 |
| Day 5 | 29,000 | 5,600 |
| Day 6 | 37,900 | 8,900 |
| Day 7 | 44,300 | 6,400 |
Step 6 of 12Practice · Work it out
What does this program print?
``
total = 0
for n in range(1, 6):
total += n * 2
print(total)
``
Step 7 of 12Practice · Code challenge · Python
Code challenge · Python
A game rewards daily streaks: day 1 gives 10 points, day 2 gives 20, day 3 gives 30, and so on. Complete streak_points(days) so it returns the total points for a streak of days days. Use a for loop with an accumulator.
For example, streak_points(3) returns 60 (10 + 20 + 30). A streak of 0 days earns 0.
The def line and the return are already written for you; you will learn exactly how they work in the Functions lesson. Fill in the middle.
streak_points(3)streak_points(1)streak_points(7)streak_points(0)
Step 8 of 12Try the calculator
Sum of a range
A loop that adds every number in range(start, stop, step). Change the values and compare with the formula output. Try start 1, stop 101, step 1: the sum 1 + 2 + … + 100.
- How many numbers the loop visits
- 10
- Last number visited
- 10
- Sum of all numbers visited
- 55
Step 9 of 12Learn
Looping over strings
A for loop can walk through more than numbers. Give it a string, and the loop variable takes each character in turn:
for letter in "LOOP":
print(letter)This prints L, O, O and P on separate lines. Combine it with an accumulator to analyze text:
word = input("Word: ").lower()
vowels = 0
for ch in word:
if ch in "aeiou":
vowels += 1
print(f"{word} has {vowels} vowels")The in operator checks membership: ch in "aeiou" is True when ch is one of those five letters. Calling .lower() first means capital vowels count too.
Loops can also contain loops. A nested loop runs its inner loop completely for every pass of the outer loop, which is how you'd print a multiplication table or check every square on a game board. An outer loop of 3 and an inner loop of 4 runs the inner block 3 × 4 = 12 times.
Step 10 of 12Practice · Work it out
How many times does the word "beep" get printed?
``
for row in range(3):
for col in range(5):
print("beep")
``
Step 11 of 12Practice · True or false
In this loop, total = 0 belongs inside the loop body so the total starts fresh for each number.
``
for n in range(5):
total = 0
total += n
``
Step 12 of 12Practice · Put in order
Arrange the lines to count how many letters "s" appear in a word the user types.
Drag the items, or use the arrow buttons, to put them in order.
- count += 1
- count = 0
- word = input("Word: ")
- for ch in word:
- print(count)
- if ch == "s":
Lesson complete!