Python Basics · Repeating Work · lesson 10 of 12
for loops and range()
about 12 minutes · free · runs in your browser
Step 1 of 2
Looping a known number of times
When you know how many repetitions you need, for is clearer than while — there is
no counter to forget to increment.
for i in range(5):
print(i)
That prints 0, 1, 2, 3, 4. range(5) produces five numbers starting at zero and
stopping before five. Almost every off-by-one bug in Python comes from forgetting one
half of that sentence.
range takes up to three arguments:
range(5)→ 0, 1, 2, 3, 4range(2, 6)→ 2, 3, 4, 5range(0, 10, 2)→ 0, 2, 4, 6, 8
for also walks straight through a string or a list:
for letter in "cat":
print(letter)
Your turn: put the squares of 1 to 5 in squares, in order — [1, 4, 9, 16, 25].
You start from this, and edit it in the browser:
squares = []
# Append the square of each number from 1 to 5.
Step 2 of 2
Accumulating a result
The most common loop shape in any language: start with an empty answer, walk the data, and build the answer up as you go.
total = 0
for price in prices:
total += price
The variable after for takes each value in turn — you never index by hand.
Your turn: write count_vowels(text) returning how many vowels the text contains.
Count both cases, so "Apple" gives 2.
You start from this, and edit it in the browser:
def count_vowels(text):
# Count a, e, i, o and u in either case.
pass