Counting loops: for and range

When you know how many times to repeat, use a for loop. Learn range with one, two and three numbers, loop over the letters of a string, and build totals and patterns.

Lesson · 15 min

In this lesson you will

  • Write a for loop over range() and say how many times it runs
  • Predict the numbers produced by range(stop), range(start, stop) and range(start, stop, step)
  • Explain why range stops one before its stop number
  • Loop over the characters of a string
  • Choose between for and while

The while loops in the last lesson all followed the same pattern: set up a counter, check it, do the work, add one. That pattern is so common that Python has a loop that does the counting for you: the for loop.

for and range

for i in range(5):
    print("Hello number", i)

Read it as “for each i in the numbers 0 to 4, run the block”. On each iteration, Python sets the loop variable i to the next number, then runs the indented block. No counter to set up, no += 1 to forget, so no accidental infinite loops.

Compare it with the while version that does the same job:

i = 0
while i < 5:
    print("Hello number", i)
    i = i + 1

Same output, three fewer things to get wrong.

What range gives you

range(5) produces the numbers 0, 1, 2, 3, 4. Two surprises for beginners:

  1. It starts at 0, not 1. Programmers count from zero a lot, and you’ll see why in the section on collections.
  2. It stops before the number you give it. range(5) never reaches 5.

The upside of both: range(5) gives exactly five numbers. range(n) always runs a loop n times.

You can give range up to three numbers:

CallNumbers producedMeaning
range(5)0, 1, 2, 3, 4from 0, stop before 5
range(2, 6)2, 3, 4, 5from 2, stop before 6
range(1, 10, 2)1, 3, 5, 7, 9from 1, in steps of 2
range(10, 0, -3)10, 7, 4, 1count down in steps of 3
range(5, 2)nothingalready past the stop

The visualiser below shows each number a range produces as a tile. Press Step to run one iteration at a time, and move the sliders to try other ranges. Predict the tiles before you let go of a slider.

Loading the interactive graphic…

Range of five hands the for loop five numbers, one per tile. They start at zero.

To see a range all at once in code, wrap it in list():

print(list(range(5)))
print(list(range(2, 6)))
print(list(range(1, 10, 2)))
print(list(range(10, 0, -3)))

Counting from 1

Want 1 to 10 instead of 0 to 9? Start at 1 and stop one past the last number you want:

for n in range(1, 11):
    print(n, "x 7 =", n * 7)

That’s a whole times table in three lines. Change the 7 to any number you like.

Totals with for

The running total from the last lesson gets shorter too:

total = 0
for n in range(1, 101):
    total = total + n
print(total)

The visualiser can show this as well: tick Keep a running total and step through.

Building patterns

The loop variable is just a variable, so you can use it in calculations, including string repetition:

for row in range(1, 6):
    print("*" * row)

Can you change it to print the triangle upside down? (Hint: count down with a negative step.)

Looping over a string

for doesn’t only work with range. It can walk through anything that holds a sequence of items. A string is a sequence of characters, so a for loop visits each one in turn:

word = "Python"
for letter in word:
    print(letter)

Combine that with an if and you can count things:

sentence = "the quick brown fox jumps over the lazy dog"
vowels = 0
for ch in sentence:
    if ch == "a" or ch == "e" or ch == "i" or ch == "o" or ch == "u":
        vowels += 1
print("Vowels:", vowels)

In the section on collections you’ll loop over lists of names, prices and scores in exactly the same way.

for or while?

  • Use for when you know what you’re looping over: a number of times, the characters of a string, later the items in a list.
  • Use while when you only know when to stop: until the guess is right, until the savings reach a target.

When both would work, for is usually shorter and safer.

Your turn

Exercise · Python

Sum of multiples

Use a for loop with range to add up every multiple of 3 or 5 from 1 to 50, including 50. (Multiples of 3 are 3, 6, 9, …; multiples of 5 are 5, 10, 15, …. Numbers like 15 that are both count once.)

Store the answer in total, and also count how many numbers you added in count.

total = 0
count = 0
for n in range(1, 50):
    pass  # replace this line with your check

print(total, count)

Check yourself

Self-check · 4 questions

for loops and range

1. Which numbers does range(4) produce?
2. Which numbers does range(2, 10, 3) produce?
3. How do you loop over the numbers 1 to 10, including 10?
4. What does for ch in "hey": print(ch) print?