Grade by Grade
A. Programming Concepts and Skills · Programming Basics: Data, Decisions and Loops

Counted Repetition: for Loops and range

A2.2 A1.3 A4.2About 70 minutes
Learning goals
  • I can write for loops using range with one, two or three arguments.
  • I can predict exactly which values a range produces, including where it stops.
  • I can use a for loop to total, count and build strings.
  • I can loop over the characters of a string.
  • I can choose between a for loop and a while loop.

Words to know

for loop
A loop that runs its body once for each value in a sequence, such as the numbers from range or the characters of a string.
range(start, stop, step)
Produces whole numbers from start up to, but not including, stop, going up by step. Defaults: start 0, step 1.
counted (definite) loop
A loop whose number of iterations is known before it starts. A for loop is the usual choice.
conditional (indefinite) loop
A loop that repeats until something happens, with no known count. A while loop is the usual choice.
loop variable
The variable after for that takes the next value at the start of each iteration.

When you know how many times

A coach says: "Skate 10 laps." You know the count before you start. A while loop can do this (start a counter, test it, add 1), but it is easy to forget a part. The for loop handles the counting for you.

for lap in range(1, 6):
print("Lap", lap)
print("Done skating!")

lap takes the values 1, 2, 3, 4, 5. The body runs once for each. Output, line by line: Lap 1 | Lap 2 | Lap 3 | Lap 4 | Lap 5 | Done skating!

range in detail

  • range(5): 0, 1, 2, 3, 4. Five values, starting at 0.
  • range(1, 6): 1, 2, 3, 4, 5. Starts at 1, stops before 6.
  • range(0, 21, 5): 0, 5, 10, 15, 20. The third argument is the step.
  • range(10, 0, -2): 10, 8, 6, 4, 2. A negative step counts down; it stops before 0.
  • range(5, 1): nothing at all. Counting up from 5 can never get below 1, so the loop body runs zero times.

The number of values in range(a, b) is b - a. To include a last value n, write range(..., n + 1).

range(2,11,3)start: 2(included)stop: 11(NOT included)step: 3(add 3 each time)gives 2, 5, 8
The three arguments of range. It starts at start, goes up by step, and stops before stop. 11 is never reached; the next value after 8 would be 11, which is not less than 11.
0123456789101112+3+3
range(2, 11, 3) on a number line: 2, 5, 8. The next jump would land on 11, which is not less than the stop value 11, so it is left out.

Patterns with for

The same patterns from while loops work, with less code:

  • Total (accumulator): total = 0 before the loop; total += i inside.
  • Count: count = 0 before; count += 1 inside an if.
  • Build a string: result = "" before; result += something inside.

Do not change the loop variable inside a for loop. Python sets it again from the range at the start of every iteration, so the change has no lasting effect and only confuses readers.

Convention: use a meaningful name (lap, day, month), or i, j, k for plain counters. If the value is not used at all, the convention is _: for _ in range(3): print("Hip hip hooray!").

Worked example

Example 1: Totals and counts

Write a program that finds the sum of the whole numbers from 1 to 100, and counts how many of them are multiples of 7.

  1. The values are 1 to 100, so the range is range(1, 101).
  2. Two accumulators start at 0: total and sevens.
  3. Code: - total = 0 - sevens = 0 - for n in range(1, 101): -     total += n -     if n % 7 == 0: -         sevens += 1 - print(total, sevens)
  4. Check by reasoning: 1 + 100, 2 + 99, ... makes 50 pairs of 101, so 5050. Multiples of 7 up to 100: 7 × 1 to 7 × 14 (98), so 14.

Output: 5050 14.

Looping over a string

A for loop can also go through the characters of a string, one per iteration: for ch in "SNOW": gives "S", then "N", "O", "W". In Lesson 6 you shifted one letter with a Caesar cipher. Now you can encode a whole message. (You will learn many more string tools in the unit Arrays and Subprograms.)

S+3VN+3QO+3RW+3Zchnewiteration 1, 2, 3, 4: one character each time
for ch in message: takes the characters one at a time. Shifting each by 3 turns SNOW into VQRZ. (None of these letters needs to wrap around; Y, for example, would become B.)
message = "SNOW DAY"
shift = 3
secret = ""
for ch in message:
if "A" <= ch <= "Z":
secret += chr((ord(ch) - 65 + shift) % 26 + 65)
else:
secret += ch
print(secret)

Characters that are not capital letters (here, the space) are copied unchanged. Notice the if nested in the loop: Lesson 13 does much more of this. Output: VQRZ GDB

Worked example

Example 2: A times table

Print the 7 times table from 7 × 1 to 7 × 10, lined up neatly.

  1. The multipliers are 1 to 10: range(1, 11).
  2. Use an f-string with a width so the answers line up: {7 * i:>3}.
  3. Code: - for i in range(1, 11): -     print(f"7 x {i:>2} = {7 * i:>3}")
  4. The first lines are 7 x 1 = 7 and 7 x 2 = 14; the last is 7 x 10 = 70.

Ten lines, with the numbers right-aligned in columns.

for or while?

  • Use for when the number of repetitions is known before the loop starts (a count, a range of numbers, each character of a string). It cannot become infinite by accident.
  • Use while when you repeat until something happens and the count is unknown: until a sentinel, until valid input, until a goal is reached.

Any for loop over a range can be rewritten as a while loop with an initialize, test and update. The for version is shorter and safer.

Just for fun

A programmer tried to count sheep to fall asleep: 0, 1, 2, ..., 99.

She stayed awake all night waiting for sheep number 100. She had used range(100).

Hands-on activity

Skip counting with coins, and a secret message

You need: a handful of coins (nickels or any one kind), paper and Python.

  1. Lay out coins one by one and count the total value by 5s: 5, 10, 15, ... up to 50 cents. Write the range that produces exactly those numbers, and test it with a for loop that prints each value with print(value, end=" ").
  2. Count backwards from 50 to 5 by 5s. Write that range too.
  3. Write a program that asks for a number of nickels and prints the running total after each coin (use a for loop and an accumulator).
  4. Write a 2-to-4-word message to someone in your family in capital letters, encode it with the Caesar program in this lesson (shift 3), and give them the secret text. Let them decode it by changing shift to -3.

What to look for: step 1 is range(5, 51, 5) and step 2 is range(50, 0, -5) (any stop from 1 to 4 also works, since it stops before the stop value). Decoding with shift −3 works because % 26 turns a negative position into the right letter (for example, A shifted by −3 is X).

Your turn

1

List the values of range(4), range(3, 8) and range(1, 10, 4).

2

List the values of range(20, 5, -5).

3

Write a range that gives 10, 20, 30, ..., 100.

4

What is printed?

  • total = 0
  • for k in range(1, 5):
  •     total += k * k
  • print(total)
5

Write a loop that prints * 8 times on one line.

6

How many times does the body run?

  • for i in range(3, 3):
  •     print(i)
7

Would you use for or while to (a) print a 12-month calendar, (b) ask for a password until it is correct?

More practice: warm-up

1

What is the first value of range(6)?

2

Is 10 included in range(1, 10)?

3

How many values are in range(2, 9)?

4

What does the third argument of range control?

5

What is printed?

  • for ch in "eh":
  •     print(ch)

More practice: on your own

1

Write a program that reads n and prints the factorial n! = 1 × 2 × ... × n.

2

Write a loop that counts the vowels in a string text (lower case).

3

Rewrite as a for loop:

  • i = 10
  • while i > 0:
  •     print(i)
  •     i -= 2
4

What is printed?

  • word = ""
  • for ch in "loop":
  •     word = ch + word
  • print(word)
5

Write a loop that prints a table of Celsius temperatures from −30 to 30 in steps of 10, with the Fahrenheit value to 1 decimal place.

Challenge

1

Write a program that reads a positive integer and prints whether it is prime, using a for loop to count its divisors.

2

Print the first 10 Fibonacci numbers (1, 1, 2, 3, 5, ...), where each number is the sum of the two before it.

3

Decode the Caesar message KRFNHB (shift 3) by hand, and explain how % 26 makes decoding with a shift of −3 work for the letter A.

Check your understanding

Quiz

1.

What does range(2, 8, 2) produce?

2.

How many times does for i in range(10): run its body?

3.

Which range counts down 5, 4, 3, 2, 1?

4.

What is the starting value for a product accumulator?

5.

What does for ch in "abc": print(ch, end="") (body on its own line) show?

6.

Which task suits a while loop better than a for loop?

For parents and teachers

Big idea: expectation A2.2 (repetition) with counted loops; strings are built with assignment and concatenation (A1.3); meaningful loop variable names and indentation follow A4.2 conventions.

How to help: ask your teen to predict a range before running it, especially the last value. The coin activity makes the "stops before stop" rule concrete.

Common difficulties:

  • Off-by-one: range(1, 10) does not include 10.
  • Starting a product at 0.
  • Putting the print of a total inside the loop (it prints every time) instead of after it (no indent).
  • Trying to count down with a positive step, which gives an empty range.