Python Programming I
Senior 4 · ICT
Python Programming I
Lesson 5 of 5
25 min
Some repetition is open-ended: keep going until the money doubles. Much more is counted: once for each of the 40 students in the class, once for each day of the week, once for each of Rwanda's five provinces. For those, Python has the for loop. It takes a sequence of values and runs its block once for each value in turn, with no loop variable to start, test or change by hand, so it cannot accidentally run for ever.
Definition
for loop: for variable in sequence: followed by an indented block; the block runs once for each item of the sequence, with the variable set to that item.
Iterable: anything a for loop can step through: a range of numbers, a string (character by character), a list of values.
range(start, stop, step): the whole numbers from start up to but not including stop, counting in steps of step. range(stop) starts at 0 with step 1.
Nested loop: a loop inside the block of another loop; the inner loop runs completely for each pass of the outer one.
| Call | Values | How many |
|---|---|---|
range(5) | 0, 1, 2, 3, 4 | 5 |
range(1, 6) | 1, 2, 3, 4, 5 | 5 |
range(2, 11, 2) | 2, 4, 6, 8, 10 | 5 |
range(10, 0, -1) | 10, 9, …, 1 | 10 |
The pseudocode FOR i ← 1 TO n becomes for i in range(1, n + 1):. The "+ 1" is needed because the stop value is left out.
Press Run. The block runs 10 times, with i = 1, 2, …, 10. Change the 7 to another number, or the range to range(1, 13), and run again.
Worked example 1: an accumulator
Add the whole numbers from 1 to 100.
total = 0
for n in range(1, 101):
total += n
print(total)The accumulator starts at 0 before the loop, and each pass adds the current n. Output: 5050. Check with the formula for the sum of the first whole numbers: . Changing total += n to total += n * n with range(1, 11) gives the sum of the first ten squares, .
A for loop can step through any sequence, not only numbers. Over a string it gives one character at a time; over a list (values in square brackets, separated by commas) it gives one item at a time. Since 1 January 2006, Rwanda has been divided into four provinces and the City of Kigali.
Run it. The first loop prints the five names, numbered; the second visits the 9 letters of "Nyamagabe" one by one and counts the 4 vowels. letter.lower() turns a capital into a small letter, so "A" would count too, and in asks whether the letter appears in the string "aeiou".
Put a loop inside a loop to work in rows and columns. The inner loop runs all the way through for every single pass of the outer loop, so the body of the inner loop runs (outer passes) × (inner passes) times.
Run it. The outer loop makes 5 rows; for each row the inner loop prints 5 products on the same line (end="" stops print from starting a new line), then the empty print() ends the row. The inner body runs \( 5 \times 5 = 25 \) times.
Worked example 2: for or while?
| Task | Loop | Why |
|---|---|---|
| Print a receipt line for each of 12 items | for | The number of passes is known: range(12). |
| Keep asking until a valid mark is typed | while | Nobody knows how many tries it will take. |
| Count the letters "a" in a sentence | for | Step through every character of the string. |
| Years until savings double | while | Stop when a condition is met, not after a fixed count. |
A for loop can also stop early with break: for n in range(51, 100): if n % 7 == 0: print(n); break finds the first multiple of 7 above 50, which is 56, and stops.
Corey Schafer: Python Tutorial for Beginners 7, Loops and Iterations, For and While Loops. Watch for loops over lists and range(), then break and continue, then while loops, and compare them with this lesson and the last.
Warning
The stop value is never reached. range(1, 10) ends at 9. To include 10, write range(1, 11). Check the last value every time.
Initialise accumulators before the loop. total = 0 inside the loop resets the total on every pass, and only the last value survives.
Do not change the loop variable inside a for loop to control it. Assigning to i in the block does not change the next value range gives; use a while loop if you need that control.
Tip
Count the passes. range(start, stop, step) with a positive step gives values: for range(2, 11, 2), , rounded up to 5. A quick count tells you whether your loop runs the right number of times before you run it.
Practice
range(4); (b) range(3, 8); (c) range(0, 20, 5); (d) range(5, 0, -2).range(len(word) - 1, -1, -1).print run? for a in range(4): then, inside it, for b in range(3): print(a, b).*, **, ***, **** (four lines).for i in range(1, 10): total = 0; total += i (the two statements in the block) and then print(total). It prints 9 instead of 45. Explain the bug and evaluate whether a while loop would have avoided it.for n in range(1, 20, 2): print(n).n = int(input("n: ")); total = 0; for i in range(1, n + 1): total += i; print(total). For 10 it prints 55.word = input("Word: "); for i in range(len(word) - 1, -1, -1): print(word[i]). (The stop −1 lets the loop reach index 0.)for row in range(1, 5): then for star in range(row): print("*", end=""), then print() after the inner loop. (Or simply print("*" * row).)gifts = [1500, 2000, 1200, 2500, 1800]; total = 0; for g in gifts: total += g; print(total, total / len(gifts)): total 9000, average 1800.0.total = 0 is inside the loop, so it is reset on every pass; only the last value, 9, survives. Moving it above the loop fixes it. A while loop would not help: the mistake is where the accumulator is initialised, and the same bug can be made in any loop.Key points
for variable in sequence: runs its block once per item: numbers from range(), characters of a string, or items of a list.range(start, stop, step) includes start and excludes stop; FOR i ← 1 TO n is for i in range(1, n + 1).break.Further reading
print onwards.Sources and credits
This lesson adapts CC BY-SA material and is shared under CC BY-SA 4.0.
# The 7 times table: FOR i <- 1 TO 10 in pseudocode
for i in range(1, 11):
print(f"7 x {i:2} = {7 * i:3}")# Over a list: Rwanda's provinces and the City of Kigali
provinces = ["City of Kigali", "Northern Province", "Southern Province",
"Eastern Province", "Western Province"]
number = 1
for name in provinces:
print(number, name)
number += 1
# Over a string: count the vowels in a district name
district = "Nyamagabe"
vowels = 0
for letter in district:
if letter.lower() in "aeiou":
vowels += 1
print(district, "has", vowels, "vowels")# A 5 x 5 multiplication grid
for row in range(1, 6):
for col in range(1, 6):
print(f"{row * col:4}", end="")
print() # new line after each rowQuick check
Which values does range(1, 6) produce?