Show contents
Chapter 4 of 6 · 15 min
The for loop and range()
By the end of this chapter, you'll be able to
- Go through the items of a list with for
- Repeat an action a set number of times with range()
- Compute a total or a counter in a loop
- Predict the exact values produced by range()
Going through a list with for
A list is a sequence of values between square brackets: ["Ana", "Kwame", "Mei"]. The for loop takes each item, one after the other, stores it in a variable, and runs the indented block.
cities = ["Abidjan", "Montréal", "Hanoi"]
for city in cities:
print("Hello from", city)
Hello from Abidjan
Hello from Montréal
Hello from Hanoi
The variable city changes value on each round (also called an iteration).
Counting with range()
range(n) produces the numbers from 0 to n - 1. range(start, stop) goes from start to stop - 1. The stop value is never included.
range(1, 5) is used up: we leave the loop and display 10.
Text description of the animation
- We want to add 1 + 2 + 3 + 4. range(1, 5) will produce 1, 2, 3 and 4: never 5.
- We set a total to 0, before the loop.
- Round 1: n takes the first value, 1.
- We add n to the total.
- Round 2: n is 2.
- The total becomes 3.
- Round 3: n is 3.
- The total becomes 6.
- Round 4: n is 4, the last value of range(1, 5).
- The total becomes 10.
- range(1, 5) is used up: we leave the loop and display 10.
for i in range(1, 6):
print("7 x", i, "=", 7 * i)
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
range(start, stop, step) also accepts a step: range(0, 10, 2) gives 0, 2, 4, 6, 8.
Your turn
Mini-lab: the averagePython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Worked exercise: counting vowels
Write a program that counts the vowels (a, e, i, o, u, y) in the word "programming". A for loop over a text goes through its characters one by one.
Hint 1
Hint 2
letter in "aeiouy" is True if letter is part of that text.Show the solution and common mistakes
word = "programming"
vowels = 0
for letter in word:
if letter in "aeiouy":
vowels = vowels + 1
print(vowels)
3
Common mistakes:
- Putting
vowels = 0inside the loop: the counter goes back to zero for every letter. - Forgetting to indent the
ifunder thefor: the test would only run once, after the loop.
Summary
- 1for goes through the items of a list or the characters of a text.
- 2range(start, stop) produces the integers from start to stop - 1.
- 3To compute a total, set up a variable before the loop and update it on each round.
- 4A result that's off by one is often a bounds mistake.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.