Find a course

Module 3: Decisions and LoopsLesson 6 of 1012 min

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.

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 i takes 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()

  1. 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.

  2. 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, write range(1, 11).

  3. 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)   # 10

Notice 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.

An accumulator over one week of stepsLine chart with 7 categories: Day 1: Running total 5,200, Steps that day 5,200; Day 2: Running total 11,300, Steps that day 6,100; Day 3: Running total 16,100, Steps that day 4,800; Day 4: Running total 23,400, Steps that day 7,300; Day 5: Running total 29,000, Steps that day 5,600; Day 6: Running total 37,900, Steps that day 8,900; Day 7: Running total 44,300, Steps that day 6,400.010k20k30k40k50kStepsDay 1Day 2Day 3Day 4Day 5Day 6Day 7
Illustrative numbers. Each loop pass adds that day's steps to total.
An accumulator over one week of steps
ItemRunning totalSteps that day
Day 15,2005,200
Day 211,3006,100
Day 316,1004,800
Day 423,4007,300
Day 529,0005,600
Day 637,9008,900
Day 744,3006,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.

Real Python, running in a sandbox in your browser.
  • 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.

  1. count += 1
  2. count = 0
  3. word = input("Word: ")
  4. for ch in word:
  5. print(count)
  6. if ch == "s":