Repeating with for¶
Goal: run the same block of code once for each item in a sequence.
Why this matters¶
Suppose you want to print the numbers 1 to 100. You could write a hundred print lines.
Now suppose you want 1 to a million. Loops are how a program does something many times without you writing it many times.
They are the first idea in this course that makes computers feel powerful.
Looping over a string¶
You already know strings are sequences of characters. A for loop visits each one in turn:
Read the first line as "for each letter in Python, do the following". Python takes the first character,
stores it in the variable letter, runs the indented block, then takes the next character and does it again,
until it runs out. After the loop, the program carries on with the unindented line.
The shape should look familiar from if: a line ending in a colon, then an indented block.
The block is called the loop body, and each run of the body is one iteration.
The variable name letter is your choice. Pick something that describes one item: letter, character, digit.
Looping a number of times¶
To loop over numbers rather than characters, use range():
range(5) produces five numbers, starting at 0 and stopping before 5. Yes, it starts at zero, just like string indexes,
and yes, the stop value is not included, just like slices. Python is consistent about this once you know the rule.
range() accepts up to three values, range(start, stop, step):
for n in range(1, 6):
print(n)
print("---")
for n in range(0, 20, 5):
print(n)
print("---")
for n in range(3, 0, -1):
print(n)
print("Liftoff!")
range(1, 6)starts at 1 and stops before 6.range(0, 20, 5)goes up in steps of 5.range(3, 0, -1)counts down, using a negative step.
The off-by-one rule
To loop from 1 to n inclusive, write range(1, n + 1). Forgetting the + 1 is the most common loop mistake there is,
and even experienced programmers make it.
Sometimes you do not care about the number at all, you just want to repeat something:
The variable is still there, it just goes unused. Programmers often call it i in that case, short for index.
The accumulator pattern¶
Loops become truly useful when each iteration builds on the last. The classic example is adding up numbers:
total = 0
for n in range(1, 5):
total += n
print(f"Added {n}, total is now {total}")
print(f"Final total: {total}")
Added 1, total is now 1
Added 2, total is now 3
Added 3, total is now 6
Added 4, total is now 10
Final total: 10
Three parts make up this pattern, and you will use it constantly:
- Before the loop, create a variable with a starting value:
total = 0. - Inside the loop, update it:
total += n. - After the loop, use the result.
The variable total is called an accumulator because it accumulates a result across iterations.
Creating it before the loop matters. If total = 0 were inside the loop body, it would be reset to zero every iteration.
Counting things¶
Counting is the same pattern with += 1, usually combined with an if:
sentence = "the quick brown fox"
spaces = 0
for character in sentence:
if character == " ":
spaces += 1
print(f"Words: {spaces + 1}")
The loop looks at every character, and the counter only goes up for the ones that are spaces.
Four words have three spaces between them, hence the + 1.
Notice the indentation here: the if is indented inside the for, and the spaces += 1 is indented inside the if.
Blocks nest, and each level is another four spaces.
Try it¶
Print a countdown from 10 to 1 using range(), then print "Happy New Year!". Then change it to count in steps of 2.
Common mistakes¶
The loop runs one time too few
range(1, 10) stops at 9. Use range(1, 11) for 1 to 10.
TypeError: 'int' object is not iterable
You wrote for i in 5: instead of for i in range(5):. A loop needs a sequence to walk through.
The total is always the last number
The accumulator is being created inside the loop body, so it resets on every iteration. Move total = 0 above the for line.
NameError after the loop
You used the accumulator after the loop but never created it before the loop, and the loop ran zero times.
Always initialize the variable before the for.
Exercises¶
- Times table. Ask for a number and print its multiplication table from 1 to 10, one line per row,
like
3 x 7 = 21. - Sum to n. Ask for a number
nand print the sum of every whole number from 1 ton. For 100 the answer is 5050. - Vowel counter. Ask for a sentence and print how many vowels it contains. Count
a,e,i,o,uin either case.
Solution 1
Solution 2
n = int(input("Add up all numbers from 1 to: "))
total = 0
for i in range(1, n + 1):
total += i
print(f"The sum of 1 to {n} is {total}.")
The n + 1 is the off-by-one rule from earlier in the lesson.
Solution 3
sentence = input("Type a sentence: ")
vowels = 0
for character in sentence.lower():
if character in "aeiou":
vowels += 1
print(f"That sentence has {vowels} vowels.")
character in "aeiou" is the in test from Module 2, checking whether a one-character string appears in the string
of vowels. Lowercasing the sentence first means A and a are both counted.
Summary¶
for item in sequence:runs the indented body once per item.range(stop)counts from 0 up to but not includingstop.range(start, stop, step)gives full control.- To include
n, writerange(1, n + 1). - The accumulator pattern: create a variable before the loop, update it inside, use it after.
- Blocks nest. An
ifinside aforis indented twice.