A. Programming Concepts and Skills · Programming Basics: Data, Decisions and LoopsCounted 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).
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.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 exampleExample 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.
- The values are 1 to 100, so the range is
range(1, 101). - Two accumulators start at 0:
total and sevens. - Code:
-
total = 0
- sevens = 0
- for n in range(1, 101):
- total += n
- if n % 7 == 0:
- sevens += 1
- print(total, sevens) - 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.
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.)
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 exampleExample 2: A times table
Print the 7 times table from 7 × 1 to 7 × 10, lined up neatly.
- The multipliers are 1 to 10:
range(1, 11). - Use an f-string with a width so the answers line up:
{7 * i:>3}. - Code:
-
for i in range(1, 11):
- print(f"7 x {i:>2} = {7 * i:>3}") - 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 funA 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 activitySkip counting with coins, and a secret message
You need: a handful of coins (nickels or any one kind), paper and Python.
- 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=" "). - Count backwards from 50 to 5 by 5s. Write that
range too. - 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). - 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
1List the values of range(4), range(3, 8) and range(1, 10, 4).
0, 1, 2, 3; then 3, 4, 5, 6, 7; then 1, 5, 9.
2List the values of range(20, 5, -5).
20, 15, 10. (5 is the stop, so it is not included.)
3Write a range that gives 10, 20, 30, ..., 100.
range(10, 101, 10) (any stop from 101 to 110 works).
4What is printed?
total = 0for k in range(1, 5): total += k * kprint(total)
5Write a loop that prints * 8 times on one line.
Sample:
for i in range(8): print("*", end="")print()
The final print() ends the line. (Without a loop, string repetition does the same job.)
6How many times does the body run?
for i in range(3, 3): print(i)
Zero. The range is empty: it starts at 3 and must stop before 3.
7Would you use for or while to (a) print a 12-month calendar, (b) ask for a password until it is correct?
(a) for: 12 is known. (b) while: the number of tries is unknown.
More practice: warm-up
1What is the first value of range(6)?
2Is 10 included in range(1, 10)?
3How many values are in range(2, 9)?
4What does the third argument of range control?
The step: how much to add each time.
5What is printed?
for ch in "eh": print(ch)
e, then h, on separate lines.
More practice: on your own
1Write a program that reads n and prints the factorial n! = 1 × 2 × ... × n.
Sample:
n = int(input("n: "))product = 1for i in range(1, n + 1): product *= iprint(product)
A product accumulator starts at 1, not 0. For n = 5 it prints 120.
2Write a loop that counts the vowels in a string text (lower case).
Sample:
vowels = 0for ch in text: if ch in "aeiou": vowels += 1
For "maple syrup" it gives 3. (ch in "aeiou" is True when ch is one of those letters.)
3Rewrite as a for loop:
i = 10while i > 0: print(i) i -= 2
for i in range(10, 0, -2): with print(i) indented under it. Both print 10, 8, 6, 4, 2.
4What is printed?
word = ""for ch in "loop": word = ch + wordprint(word)
pool. Each new character is put in front, so the string is reversed: l, ol, ool, pool.
5Write 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.
Sample:
for c in range(-30, 31, 10): f = 9 / 5 * c + 32 print(f"{c:>4} C = {f:>5.1f} F")
The first line shows −30 C = −22.0 F and the last shows 30 C = 86.0 F, with the numbers right-aligned in columns.
Challenge
1Write a program that reads a positive integer and prints whether it is prime, using a for loop to count its divisors.
Sample:
n = int(input("n: "))divisors = 0for d in range(1, n + 1): if n % d == 0: divisors += 1if divisors == 2: print(n, "is prime")else: print(n, "is not prime")
A prime has exactly two divisors, 1 and itself. 1 has only one divisor, so it is correctly reported as not prime. 13 → prime; 15 → not prime.
2Print the first 10 Fibonacci numbers (1, 1, 2, 3, 5, ...), where each number is the sum of the two before it.
Sample:
a, b = 1, 1for i in range(10): print(a) a, b = b, a + b
Output: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55. The simultaneous assignment from Lesson 2 moves both values forward at once.
3Decode the Caesar message KRFNHB (shift 3) by hand, and explain how % 26 makes decoding with a shift of −3 work for the letter A.
HOCKEY. For A with shift −3: 0 + (−3) = −3, and -3 % 26 is 23 in Python (% gives a result from 0 to 25 when the divisor is 26), and 23 + 65 = 88 is X. So A becomes X, wrapping backward correctly.
Check your understandingQuiz
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 teachersBig 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.