for Loop Programs
A for loop is for the jobs where you know how many times before you start — ten rows of a table, every letter of a word, every mark in a list. Nearly all of these programs are the same three lines in a different order: start a collector, add to it inside the loop, print it after.
1Program 1 — the multiplication table of a number
Ask for a number and print its table from 1 to 10, in the form 7 x 3 = 21.
- the number,
num
- multiply it by each of 1 to 10 in turn
- ten lines, one per row of the table
# the multiplication table of any number, from 1 to 10
num = int(input('Enter a number: '))
for i in range(1, 11):
print(num, 'x', i, '=', num * i)Enter a number: 7 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70
range(1, 11), not range(1, 10). The stop value is excluded, so range(1, 10) stops at 9 and the table is one row short. A table that ends at 9 is the single commonest range() mistake — and it looks fine until somebody counts the rows.2Program 2 — the sum of the first n numbers
Ask for a number n and print the total of all the whole numbers from 1 to n.
# the sum of the first n natural numbers
n = int(input('Enter a number: '))
total = 0
for i in range(1, n + 1):
total = total + i
print('The sum of the first', n, 'numbers is', total)Enter a number: 10 The sum of the first 10 numbers is 55
total = 0Above the loop, so it is made once. Zero is the right starting value for a sum: adding it to anything changes nothing.
for i in range(1, n + 1):n + 1 as the stop, because the stop is excluded and n itself has to be counted. With n = 10 the values handed out are 1 to 10.
total = total + iThe right-hand side is worked out first — the old total plus this round's number — and the answer goes back into the same box. Ten rounds, ten additions.
print('The sum of the first', n, 'numbers is', total)At the margin, so it runs once, after the loop has finished. Indent it and you would get ten lines showing the running total.
total = 0 inside the loop and the answer becomes n. Each round would wipe the total and add just that round's number, so after the last round the total is whatever the last number was. No error — just an answer that happens to be right when n is 1.3Program 3 — the factorial of a number
The factorial of 5 is 1 × 2 × 3 × 4 × 5 = 120. Ask for a number and print its factorial.
# the factorial of a number: 5! = 1 x 2 x 3 x 4 x 5
n = int(input('Enter a number: '))
fact = 1
for i in range(1, n + 1):
fact = fact * i
print('The factorial of', n, 'is', fact)Enter a number: 5 The factorial of 5 is 120
The same shape as the sum, with one change that is the whole lesson: fact starts at 1, not 0. The starting value has to be the one that does nothing to the operation — 0 for adding, 1 for multiplying.
# the same factorial, but the collector starts at 0
n = int(input('Enter a number: '))
fact = 0
for i in range(1, n + 1):
fact = fact * i
print('The factorial of', n, 'is', fact)Enter a number: 5 The factorial of 5 is 0
0 * 1, and from then on there is no way back: every later round multiplies zero by something. The program runs perfectly and answers 0 for every number you give it.4Program 4 — count the vowels in a word
Ask for a word and count how many of its letters are vowels. Capitals count too.
# count the vowels in a word
word = input('Enter a word: ')
count = 0
for letter in word:
if letter.lower() in 'aeiou':
count = count + 1
print('The word has', count, 'vowels')Enter a word: banana The word has 3 vowels
Enter a word: rhythm The word has 0 vowels
A for loop does not need range(). Given a string it hands out one letter at a time, in order, and stops when the string runs out — so the loop counts the letters without anybody having to say how many there are.
This is also the first program here with an if inside a loop. The indentation tells the whole story: the if is indented four spaces because it belongs to the loop, and count = count + 1 is indented eight because it belongs to the if. Pull that line back to four spaces and every letter is counted, vowel or not.
5Program 5 — the highest mark in a list
A list holds five marks. Find the highest, without using max().
# the highest mark in a list, found the long way
marks = [56, 91, 43, 78, 65]
highest = marks[0]
for m in marks:
if m > highest:
highest = m
print('The marks are', marks)
print('The highest mark is', highest)The marks are [56, 91, 43, 78, 65] The highest mark is 91
The collector here is not a total but a champion: the best value seen so far. Every round asks one question — is this one better? — and replaces the champion when the answer is yes.
marks[0], not at 0. Starting at 0 looks harmless and quietly breaks the moment every mark is negative — a list of temperatures like [-4, -9, -2] would report a highest of 0, a value that is not in the list at all. The first item of the list is always a safe champion, because it is a real member of it.6Program 6 — reverse a word
Ask for a word and print it backwards.
# reverse a word, one letter at a time
word = input('Enter a word: ')
backwards = ''
for letter in word:
backwards = letter + backwards
print('Reversed:', backwards)Enter a word: python Reversed: nohtyp
The collector is a string this time, and it starts empty — '' is to joining what 0 is to adding. The trick is the order: letter + backwards puts each new letter in front of everything collected so far. Write backwards + letter instead and you rebuild the word exactly as it was.
'': 'c', then 'ac', then 'tac'. Three rounds, and the word is inside out. Tracing three rounds by hand is faster than staring at six lines.7Program 7 — the total and average of a list
A list holds five marks. Print their total and their average.
# the total and the average of a list of marks
marks = [72, 65, 88, 91, 54]
total = 0
for m in marks:
total = total + m
average = total / len(marks)
print('Total:', total)
print('Average:', average)Total: 370 Average: 74.0
len(marks) rather than 5, so adding a sixth mark to the list needs no other change. And the average is worked out after the loop — inside it, you would be dividing a part-finished total by the full count, which is not an average of anything.
sum() and len(). total = sum(marks) does the loop's job in one line, and in real code that is what you would write. Exam questions usually ask for the loop, because the loop is the part being examined — and because sum() cannot help you the moment the rule gets fussier, as it does on the continue page.8Recap
0 for a sum, 1 for a product, '' for a string, marks[0] for a champion. Inside the loop it is wiped every round.
At the margin, once. Indented, you get one line per round showing the running value — sometimes useful, rarely what was asked.
The stop is excluded. Any program whose answer is one short is nearly always this.
range() for counting, a string for its letters, a list for its items. Same loop, no length needed.
- 1
Print the table of a number from 1 to 20 instead of 1 to 10.
Hint · Only the stop value changes — and remember it is excluded.
- 2
Print all the even numbers from 1 to 50, using the loop's step rather than an
if.Hint ·
range(2, 51, 2)— the third number is how far to jump. - 3
Ask for a number and print the sum of its table (7 + 14 + … + 70).
Hint · The table program and the sum program, joined: one collector, one loop.
- 4
Count how many marks in a list are 33 or above.
Hint · A counter above the loop, an
ifinside it. The counter goes up by 1, not by the mark. - 5
Print the first ten numbers of the Fibonacci series: 0, 1, 1, 2, 3, 5…
Hint · Two variables,
aandb. Printa, then set both at once from the old pair — work the new value out before you overwrite anything.
A program totals 1 to n but has total = 0 written inside the loop instead of above it. For n = 10, what does it print?
Why does the factorial program start fact at 1?
In the reverse program, what does backwards = backwards + letter print for 'python'?