Quick check
What does this print? for ch in "hi!": with the block print(ch * 2, end=" ")
Show the answer
Answer: hh ii !! on one line. Each character in turn is repeated twice.
Ultimate Core Python · Chapter 14
This lesson goes with Episode 14 of the Ultimate Core Python course on the Core by Critic channel on YouTube.
for statementPrint each letter of a word on its own line. With while, you need an index, a condition and an update:
word = "cat"
i = 0
while i < len(word):
print(word[i])
i += 1Output
c a t
Five lines, three of them bookkeeping, and three places to make a mistake. Here is the same job with for:
word = "cat"
for letter in word:
print(letter)Output
c a t
No index. No condition. No update. Nothing to forget.
for keyword loop variable keyword the sequence colon
│ │ │ │ │
for letter in word :
print(letter) ◄── the block, run once per item
Read it as: "for each letter in word, do this."
Here is exactly what Python does:
| Pass | letter |
Prints |
|---|---|---|
| 1 | "c" |
c |
| 2 | "a" |
a |
| 3 | "t" |
t |
| — | nothing left | the loop ends |
The loop variable (letter here) is an ordinary variable. You choose its name, and Python assigns it a new value at the start of every pass. You do not create it beforehand and you do not update it yourself.
A for loop over an empty sequence simply does nothing: the block runs zero times.
for letter in "":
print("This never appears")
print("Done")Output
Done
in?Anything Python can step through one item at a time. Such a thing is called an iterable. So far you know two kinds: strings, and the lists that split() gives you (Chapter 9):
for word in "the quick brown fox".split():
print(word, len(word))Output
the 3 quick 5 brown 5 fox 3
In the coming chapters nearly every collection you meet (lists, tuples, dictionaries, sets, files) will be iterable, and this same loop will work on all of them → Chapter 25. A plain number is not iterable, because it has no items:
for i in 5:
print(i)Output
Traceback (most recent call last):
File "count.py", line 1, in <module>
for i in 5:
^
TypeError: 'int' object is not iterableTo loop five times, you need something that produces five numbers. That is what range is for.
Quick check
What does this print? for ch in "hi!": with the block print(ch * 2, end=" ")
Answer: hh ii !! on one line. Each character in turn is repeated twice.
Predict the output
What does it print?
for ch in "sun":
print(ch + ch)The loop makes one pass for each character of the string.
On each pass, ch is one character, and + joins it to itself.
It prints
ss uu nn
The loop variable gets each character in turn, so the block runs three times, one time per character.
Multiple choice
What happens when this program runs?
for i in 3:
print(i)What comes after in must be something Python can step through one item at a time.
A plain number has no items. The line is written correctly, so the problem is the type of the value.
The answer is: It stops with a TypeError
A number is not iterable, so Python raises a TypeError. To loop three times, write range(3).
Put the lines in order
Put the lines in order. The program prints each letter of the word in capitals, one per line, and prints Done at the very end.
The program in the right order prints:
Target
K I T E Done
word = "kite"print("Done")for letter in word: print(letter.upper())The word must exist before the loop can walk through it.
The indented line is the block of the loop, so it comes straight after the for line. The line that is not indented runs after the loop.
word = "kite"
for letter in word:
print(letter.upper())
print("Done")The block of a for loop is the indented part under it. A line that is not indented runs one time, after the loop has ended.
range(): numbers on demandrange(n) produces the whole numbers from 0 up to, but not including, n:
for i in range(5):
print(i, end=" ")
print()Output
0 1 2 3 4
Five numbers, starting at zero, and 5 itself is not one of them. This is the standard way to say "do this five times":
for i in range(3):
print("Hello!")Output
Hello! Hello! Hello!
If the block does not use the number at all, Python programmers often name the variable _, a single underscore, as a signal to the reader: "I need a variable here, but I do not care about its value."
To look at the numbers a range holds, hand it to list(), which collects them into a list → Chapter 25:
print(list(range(5)))
print(list(range(1)))
print(list(range(0)))Output
[0, 1, 2, 3, 4] [0] []
With two arguments, range(start, stop) begins at start:
print(list(range(1, 6)))
print(list(range(5, 10)))
print(list(range(-2, 3)))Output
[1, 2, 3, 4, 5] [5, 6, 7, 8, 9] [-2, -1, 0, 1, 2]
stop is still left out. To count from 1 to 5, you write range(1, 6).
A third argument is the step, the distance between one number and the next:
print(list(range(0, 10, 2)))
print(list(range(1, 10, 3)))
print(list(range(10, 0, -1)))
print(list(range(10, 0, -3)))Output
[0, 2, 4, 6, 8] [1, 4, 7] [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] [10, 7, 4, 1]
A negative step counts down. For that, start must be the larger number, and stop is again left out: range(10, 0, -1) ends at 1.
| Call | Produces | Example | Numbers |
|---|---|---|---|
range(stop) |
from 0, up by 1 | range(4) |
0, 1, 2, 3 |
range(start, stop) |
from start, up by 1 |
range(2, 6) |
2, 3, 4, 5 |
range(start, stop, step) |
from start, in jumps of step |
range(2, 12, 4) |
2, 6, 10 |
This should look familiar. It is exactly the slice notation from Chapter 8, s[start:stop:step], with commas where the colons were, and with the same rule that stop is not included.
For the same reasons as in slicing:
range(n) produces exactly n numbers.range(len(word)) produces exactly the valid indexes of word: 0 to len(word) - 1.range(0, 5) followed by range(5, 10) covers 0 to 9 with no gap and no overlap.If the numbers cannot get from start to stop in the direction of the step, the range is simply empty. No error:
print(list(range(5, 2)))
print(list(range(2, 5, -1)))
print(list(range(3, 3)))Output
[] [] []
An empty range means the loop runs zero times. The first line is a classic mistake: to count down from 5, you must give a negative step. range(5, 2) does not guess.
range refusesThe arguments must be whole numbers, and the step cannot be zero:
for x in range(0, 1, 0.1):
print(x)Output
Traceback (most recent call last):
File "steps.py", line 1, in <module>
for x in range(0, 1, 0.1):
~~~~~^^^^^^^^^^^
TypeError: 'float' object cannot be interpreted as an integerTo step through decimal values, loop over whole numbers and calculate the decimal from each one. This also avoids the creeping float errors you saw in Chapter 13:
for i in range(5):
print(i / 4, end=" ")
print()Output
0.0 0.25 0.5 0.75 1.0
Quick check
Write the numbers each of these produces: range(3, 8), range(0, 20, 5), range(6, 0, -2), range(4, 4).
Answer: 3 4 5 6 7; 0 5 10 15; 6 4 2; and nothing (an empty range).
Predict the output
What does it print?
for i in range(2, 9, 3):
print(i, end=" ")
print()
for i in range(4, 0, -1):
print(i, end=" ")
print()Start at the first argument and keep adding the step. Stop before the second argument.
With a negative step the numbers go down, and the stop value is still left out.
It prints
2 5 8 4 3 2 1
range(start, stop, step) begins at start, moves by step, and never includes stop.
Fill in the blank
Fill in the arguments of range so that the program prints 10 8 6 4 2.
for i in range():
print(i, end=" ")
print()The finished program prints:
Target
10 8 6 4 2
You need three arguments: the start, the stop and the step.
The numbers go down by 2, so the step is negative. The stop value must be below 2, because it is left out.
for i in range(10, 0, -2):
print(i, end=" ")
print()To count down, the start is the larger number and the step is negative. The stop value is not produced.
Multiple choice
How many passes does the loop for i in range(5, 2): make?
With two arguments, the step is 1, so the numbers go up.
Can you get from 5 to 2 by counting up? If not, the range is empty, and that is not an error.
The answer is: 0
range(5, 2) is an empty range, so the block never runs. To count down you must give a negative step.
for or while?Both can do anything the other can. Choosing well makes the code say what you mean.
total = 0
for number in range(1, 6):
total += number
print(total)Output
15
Compare this with the while version in Chapter 13: the start, the condition and the update have all moved into the single phrase range(1, 6). The body contains only the real work.
for |
while |
|
|---|---|---|
| Repeats | once for each item | as long as a condition is true |
| How many passes? | known when the loop starts | not known in advance |
| Counter | handled for you | you manage it |
| Can it run for ever by accident? | no | yes |
| Typical jobs | every character, every number from 1 to n, every line of a file | until the user quits, until the input is valid, until a value is reached |
The rule of thumb:
for. This is called a definite loop: the amount of work is fixed before it starts.while. This is an indefinite loop.Asking for a password until it is right: while. Printing a 12-times table: for. Taking the digits off a number with % 10 and // 10: while. Looking at each character of the text of that number: for.
Multiple choice
A loop whose amount of work is fixed before it starts has a special name. Which one?
The section gives two names: one for "for each" loops and one for "keep going until" loops.
A for loop knows its number of passes when it starts.
The answer is: A definite loop
A for loop is a definite loop: the sequence it walks through is known at the start. A while loop is an indefinite loop.
Put the lines in order
Put the lines in order. The program adds the numbers 1 to 4 and prints the total one time.
The program in the right order prints:
Target
10
for number in range(1, 5):total = 0 total += numberprint(total)The total must exist before the loop adds to it.
The print line is not indented, so it runs after the loop and not on every pass.
total = 0
for number in range(1, 5):
total += number
print(total)Create the accumulator before the loop, update it inside the loop, and use it after the loop.
for formEvery pattern from Chapter 13 has a shorter for version.
n = int(input("Add the numbers from 1 to: "))
total = 0
for number in range(1, n + 1):
total += number
print("Total:", total)Output
Add the numbers from 1 to: 100 Total: 5050
Notice the n + 1. To include n, the stop value must be one past it. This is the single most common thing to get wrong with range.
product = 1
for number in range(1, 6):
product *= number
print(product)Output
120
How many vowels are in a sentence? Look at each character and count the ones that pass a test:
sentence = "Programming is fun"
vowels = 0
for ch in sentence.lower():
if ch in "aeiou":
vowels += 1
print("Vowels:", vowels)Output
Vowels: 5
ch in "aeiou" asks whether the character is one of those five letters, using the membership test from Chapter 5. The sentence is lowercased once, before the loop, so capitals are counted too.
A string can be an accumulator too. Start with the empty string and add to it. This removes every space:
text = "one two three"
result = ""
for ch in text:
if ch != " ":
result += ch
print(result)Output
onetwothree
Where you add the new piece decides the order. Adding at the front reverses the string:
word = "stressed"
backwards = ""
for ch in word:
backwards = ch + backwards
print(backwards)Output
desserts
| Pass | ch |
backwards after |
|---|---|---|
| 1 | s |
s |
| 2 | t |
ts |
| 3 | r |
rts |
| 4 | e |
erts |
| ... | ... | ... |
| 8 | d |
desserts |
(You already know the shortcut, word[::-1]. The loop shows what that shortcut does.)
Which character of a word comes last in the alphabet?
word = "python"
latest = word[0]
for ch in word:
if ch > latest:
latest = ch
print(latest)Output
y
The "best so far" starts as the first character, not as some made-up value. That way it is always a real item from the data.
Chapter 9 shifted a single letter along the alphabet. With a loop you can encode a whole message:
message = "meet me at noon"
shift = 3
secret = ""
for ch in message:
if ch.isalpha():
position = ord(ch) - ord("a")
secret += chr(ord("a") + (position + shift) % 26)
else:
secret += ch
print(secret)Output
phhw ph dw qrrq
Each letter is moved three places on, wrapping round at z. Anything that is not a letter (here, the spaces) is copied unchanged. To decode, run the same loop with a shift of -3.
Quick check
What does this build? out = "" then for ch in "abc": with the block out = out + ch + "-"
Answer: "a-b-c-". Note the extra hyphen at the end: a separator added after every item leaves one too many. "-".join("abc") from Chapter 9 avoids that.
Predict the output
What does it print?
code = "b2c40"
result = ""
count = 0
for ch in code:
if ch.isdigit():
result += ch
count += 1
print(result)
print(count)Only the characters that are digits pass the test.
result collects those characters in order, and count goes up by 1 for each of them.
It prints
240 3
A string and a number can both be accumulators: one collects the digits, the other counts them.
Fill in the blank
Fill in the stop value so that the loop adds every number from 1 to n, with n included.
n = 6
total = 0
for number in range(1, ):
total += number
print(total)The finished program prints:
Target
21
The stop value of a range is never produced.
To include n, the stop value must be one past it.
n = 6
total = 0
for number in range(1, n + 1):
total += number
print(total)range(1, n) ends at n - 1. Writing n + 1 as the stop value makes n the last number.
Fix the bug
This program should print the product of all the numbers from 1 to the number the user types. For 5 it should print 120, but it always prints 0. Fix it.
With the reply 5, the program prints the lines below. Your program must print exactly these lines.
Example run
120
Output
What is zero times any number?
A sum starts at 0. What is the right starting value for a product?
n = int(input("Multiply the numbers from 1 to: "))
product = 1
for number in range(1, n + 1):
product *= number
print(product)Multiplying by 0 always gives 0, so a product accumulator must start at 1.
Write code
Count one letter. Ask for a sentence, then ask for one letter. Use a loop to count how many times that letter is in the sentence. Capital and small letters count as the same letter. Print the count.
With the replies Tokyo to Toronto then t, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Count: 4
Output
Lowercase both replies one time, before the loop.
Create count = 0 before the loop. Inside the loop, add 1 when the character equals the letter.
sentence = input("Sentence: ").lower()
letter = input("Letter: ").lower()
count = 0
for ch in sentence:
if ch == letter:
count += 1
print("Count:", count)This is the counting pattern: look at every character and count the ones that pass a test.
Write code
Add the digits. Ask for a line of text. Add up every digit that is in the text and print the sum. For Room 12, floor 34 the digits are 1, 2, 3 and 4. If the text has no digit, print 0.
With the reply Room 12, floor 34, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Sum of digits: 10
Output
Loop over the characters and test each one with isdigit().
A digit character is still text. Convert it with int() before you add it to the total.
text = input("Text: ")
total = 0
for ch in text:
if ch.isdigit():
total += int(ch)
print("Sum of digits:", total)The loop combines two patterns: it filters the characters with a test, and it adds up the ones that pass.
Sometimes you need to know where each item is, not only what it is. Then loop over the indexes. range(len(word)) produces exactly the valid indexes of word:
word = "code"
for i in range(len(word)):
print(i, word[i])Output
0 c 1 o 2 d 3 e
You need positions when you want to:
word[i] and word[i + 1];i for both;Here is a neighbour example: does a word contain a double letter?
word = "balloon"
for i in range(len(word) - 1):
if word[i] == word[i + 1]:
print("Double letter:", word[i] * 2)Output
Double letter: ll Double letter: oo
The range is len(word) - 1, not len(word). The block looks at word[i + 1], so i must stop one short of the last index. Otherwise the final pass would reach past the end and raise an IndexError. Whenever a loop looks ahead by one, shorten the range by one.
Beginners who have just learned range(len(...)) tend to use it everywhere:
for i in range(len(word)): # works, but it is the long way round
print(word[i])
for letter in word: # the Python way
print(letter)Output
If the block only ever uses word[i] and never i on its own, loop over the string directly. It is shorter, clearer and cannot go out of range.
When you want both the position and the item, the built-in enumerate hands you the two together → Chapter 36:
for i, letter in enumerate("code"):
print(i, letter)Output
0 c 1 o 2 d 3 e
Predict the output
What does it print?
word = "planet"
for i in range(0, len(word), 2):
print(i, word[i])len(word) is 6, so the range is range(0, 6, 2).
Each line shows a position and the character at that position.
It prints
0 p 2 a 4 e
Looping over positions with a step visits only some of the characters, here every second one.
Fix the bug
This program should count the places where a letter is the same as the next letter. For balloon it should print Pairs: 2. Now it crashes on the last pass. Fix it.
With the reply balloon, the program prints the lines below. Your program must print exactly these lines.
Example run
Pairs: 2
Output
On the last pass, i is the last valid index. Is i + 1 still a valid index?
When the block looks one place forward, make the range one shorter.
word = input("Word: ")
pairs = 0
for i in range(len(word) - 1):
if word[i] == word[i + 1]:
pairs += 1
print("Pairs:", pairs)The block reads word[i + 1], so i must stop one before the last index: range(len(word) - 1).
Multiple choice
The loop compares each character with the character at the same distance from the other end. What does the program print?
word = "medium"
same = 0
for i in range(len(word)):
if word[i] == word[len(word) - 1 - i]:
same += 1
print(same)For i equal to 0, the two characters are the first one and the last one.
The loop visits every position, so a matching pair is seen two times: once from each end.
The answer is: 2
The first and the last character are equal. The loop meets that pair at position 0 and again at position 5.
Four facts about the loop variable clear up most confusion.
1. It is assigned afresh on every pass. Changing it inside the block does not affect the loop:
for i in range(3):
print("start of pass:", i)
i = 100
print("after change:", i)Output
start of pass: 0 after change: 100 start of pass: 1 after change: 100 start of pass: 2 after change: 100
In a while loop, changing the counter changes how many passes there are. In a for loop it does not. At the top of each pass, Python overwrites the loop variable with the next item, whatever you did to it. You cannot skip ahead or stay in place by changing i.
2. It holds a value, not a connection. The loop variable is just another label on the current item. Assigning to it moves the label and does nothing to the sequence.
3. It survives the loop. After the loop ends, the variable still exists, holding the last item:
for i in range(5):
pass
print(i)Output
4
This is different from while. After while i < 5, the counter is 5, one step past the limit. After for i in range(5), it is 4, the last value that was actually produced.
4. If the loop runs zero times, it is never created. for i in range(0) followed by print(i) raises a NameError (unless i already existed). It is the same trap as the variable assigned inside an if in Chapter 11.
Predict the output
What does it print?
for i in range(3):
i = i * 10
print(i)
print("Later:", i)At the top of every pass, Python gives i the next number of the range, whatever the block did to it.
After the loop, i still holds the last value it was given, and here the block gave it that value.
It prints
0 10 20 Later: 20
Changing the loop variable does not change the loop: there are still three passes. The variable survives the loop with its last value.
Multiple choice
What does this program print?
for i in range(2, 10, 3):
pass
print(i)Write the numbers the range produces: start at 2 and add 3 each time, stopping before 10.
After a for loop, the variable holds the last item that was produced, not one step past it.
The answer is: 8
The range produces 2, 5 and 8. After the loop the variable keeps the last of them.
Fix the bug
This program should add the numbers 1 to 4 and print 10. It prints a different number. Fix it.
The program prints the lines below. Your program must print exactly these lines.
Example run
10
Output
Look at the name of the loop variable. Which other variable has the same name?
At the top of every pass the loop overwrites total. Give the loop variable its own name and add that to the total.
total = 0
for number in range(1, 5):
total += number
print(total)A loop variable overwrites any variable with the same name. The accumulator and the loop variable need two different names.
break and continue in a for loopBoth work as they do in while.
break leaves the loop at once. The remaining items are never visited. This finds the first space in a string:
text = "hello world"
for i in range(len(text)):
if text[i] == " ":
print("First space at index", i)
breakOutput
First space at index 5
continue skips the rest of the current pass and moves on to the next item:
for n in range(1, 11):
if n % 3 == 0:
continue
print(n, end=" ")
print()Output
1 2 4 5 7 8 10
Here is a pleasant difference from Chapter 13. In a while loop, a continue placed before the update caused an infinite loop. In a for loop that cannot happen: moving to the next item is done by the loop itself, not by a line in the block that might be skipped.
A for loop can also have an else block, which runs when the loop finishes without a break. That is the natural way to say "I looked at everything and did not find it", and it is covered in the next chapter → Chapter 15.
Predict the output
What does it print?
for ch in "window":
if ch == "d":
break
print(ch, end="")
print()
for ch in "window":
if ch == "w":
continue
print(ch, end="")
print()break ends the whole loop. The characters after that point are never visited.
continue skips only the current pass. The loop then moves on to the next character.
It prints
win indo
break stops at the first match and leaves the loop. continue skips each match and keeps going.
Fill in the blank
Fill in the keyword so that the program prints only the odd numbers from 1 to 7.
for n in range(1, 8):
if n % 2 == 0:
print(n, end=" ")
print()The finished program prints:
Target
1 3 5 7
For an even number, the print line must be skipped, but the loop must go on.
One keyword skips the rest of the current pass and moves to the next item.
for n in range(1, 8):
if n % 2 == 0:
continue
print(n, end=" ")
print()continue skips the rest of the pass. In a for loop the next item is fetched by the loop itself, so nothing can get stuck.
Put the lines in order
Put the lines in order. The program prints the first digit that is in the text, and then stops looking.
The program in the right order prints:
Target
First digit: 7
if ch.isdigit(): print("First digit:", ch)for ch in text: breaktext = "Gate 7B, row 12"The if line belongs to the block of the loop, so it is indented one level.
Inside the if block, print first. A line placed after break in the same block would never run.
text = "Gate 7B, row 12"
for ch in text:
if ch.isdigit():
print("First digit:", ch)
breakThe loop tests each character. At the first digit it prints, and break leaves the loop so that later digits are not printed.
number = int(input("Table for: "))
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")Output
Table for: 8 8 x 1 = 8 8 x 2 = 16 8 x 3 = 24 8 x 4 = 32 8 x 5 = 40 8 x 6 = 48 8 x 7 = 56 8 x 8 = 64 8 x 9 = 72 8 x 10 = 80
A famous small test from job interviews. For the numbers 1 to 15, print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number itself otherwise:
for n in range(1, 16):
if n % 15 == 0:
print("FizzBuzz", end=" ")
elif n % 3 == 0:
print("Fizz", end=" ")
elif n % 5 == 0:
print("Buzz", end=" ")
else:
print(n, end=" ")
print()Output
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
The order of the chain is the lesson from Chapter 11: "both" must be tested first, or every multiple of 15 would be caught by the % 3 test and never reach it.
A prime is a whole number above 1 that can be divided exactly only by 1 and itself. To test n, try every possible divisor from 2 upwards and look for one that divides it exactly:
n = int(input("A whole number above 1: "))
is_prime = True
for divisor in range(2, n):
if n % divisor == 0:
print(f"{n} = {divisor} x {n // divisor}")
is_prime = False
break
print("Prime:", is_prime)Output
A whole number above 1: 91 91 = 7 x 13 Prime: False
This uses a flag, as in Chapter 13. The program assumes the number is prime until it finds evidence against it, and break stops the search at the first divisor, because one is enough. For n = 2, range(2, 2) is empty, the block never runs, and the flag correctly stays True.
String repetition from Chapter 7 turns numbers into pictures:
for size in range(1, 6):
print(f"{size} " + "#" * size)Output
1 # 2 ## 3 ### 4 #### 5 #####
Chapter 7 drew this triangle with five separate print calls and promised a shorter way. Here it is.
Multiple choice
In this chain the test for 3 comes first. What does the program print?
n = 15
if n % 3 == 0:
print("Fizz")
elif n % 5 == 0:
print("Buzz")
elif n % 15 == 0:
print("FizzBuzz")
else:
print(n)A chain runs the block of the first test that is true, and skips all the others.
15 is a multiple of 3, of 5 and of 15. Which test does Python reach first?
The answer is: Fizz
Only the first true test of a chain wins. That is why the FizzBuzz program in the chapter tests for 15 first.
Fill in the blank
Fill in the blank so that the program draws a triangle: one # on the first line, two on the second and three on the third.
for size in range(1, 4):
print("#" * )The finished program prints:
Target
# ## ###
Text times a number repeats the text.
The number of # characters must grow on every pass. Which name holds a new number on every pass?
for size in range(1, 4):
print("#" * size)The loop variable is 1, then 2, then 3, and "#" * size repeats the character that many times.
Write code
Countdown. Ask for a positive whole number. Print the numbers from that number down to 1 on one line, with a space between them. Then print Go! on the next line.
With the reply 5, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
5 4 3 2 1 Go!
Output
Counting down needs three arguments in range, and the step is negative.
The stop value is left out. Which stop value makes 1 the last number?
start = int(input("Start from: "))
for n in range(start, 0, -1):
print(n, end=" ")
print()
print("Go!")range(start, 0, -1) counts down and ends at 1, because the stop value 0 is not produced.
| The mistake | What you see | The fix |
|---|---|---|
Expecting range(5) to include 5 |
0 1 2 3 4 |
Use range(1, 6) for 1 to 5 |
Expecting range(1, n) to include n |
The last value is missing | range(1, n + 1) |
for i in 5: |
TypeError: 'int' object is not iterable |
for i in range(5): |
for i in len(word): |
The same TypeError |
for i in range(len(word)): |
Counting down without a step: range(5, 0) |
The loop does not run at all | range(5, 0, -1) |
A float in range |
TypeError: 'float' object cannot be interpreted as an integer |
Loop over integers and calculate the float |
Looking ahead with word[i + 1] over the full range |
IndexError on the last pass |
range(len(word) - 1) |
Changing i to skip items |
No effect | Use continue, or a step in range |
Forgetting the colon or the in |
SyntaxError |
for item in sequence: |
| The accumulator created inside the loop | It resets on every pass | Create it before the loop |
| Using the loop variable after an empty loop | NameError |
Do not rely on it, or set it first |
range(len(...)) when the index is not needed |
Longer, more fragile code | Loop over the items directly |
for and range work inside PythonQuestions with a Check button are checked on this page. Use the hints when you are stuck: the last step always shows the answer. The other questions show the book's answer, so that you can compare.
Check yourself
In for ch in "dog":, what is ch on each pass? How many passes are there?
"d", then "o", then "g". Three passes, one per character.
Check yourself
What numbers does range(4) produce? Why is 4 not among them?
0, 1, 2, 3. The stop value is never included, so that range(n) gives exactly n numbers and matches the valid indexes of a sequence of length n.
Check yourself
Write a range call that produces 10, 8, 6, 4, 2.
range(10, 0, -2).
Check yourself
What is the difference between range(5) and list(range(5))?
range(5) is a lazy range object that produces numbers when asked. list(range(5)) collects them into the list [0, 1, 2, 3, 4].
Check yourself
When is for the better choice, and when is while? Give one example of each.
for when the items or the number of passes are known at the start, such as every character of a string. while when the loop continues until something happens, such as asking until the input is valid.
Check yourself
Why does for i in range(1, n): not add up all the numbers from 1 to n?
range(1, n) stops at n - 1. To include n, the stop must be n + 1.
Check yourself
In a loop that compares text[i] with text[i + 1], what should the range be, and why?
range(len(text) - 1). On the last pass i + 1 must still be a valid index, so i must stop one before the final index.
Check yourself
What happens if you assign a new value to the loop variable inside a for block?
Nothing changes about the loop. At the start of the next pass, Python assigns the next item to the variable, overwriting your value.
Check yourself
What is the value of i after for i in range(3): pass? What about after i = 0 and while i < 3: i += 1?
After the for: 2, the last value produced. After the while: 3, the first value that failed the condition.
Check yourself
Why can continue cause an infinite loop in while but not in for?
In while, moving on depends on an update line in the block, which continue may skip. In for, the loop itself fetches the next item, so it always advances.
Predict the output
for i in range(2, 11, 3):
print(i, end=" ")
print()
for i in range(3, 0, -1):
print(i, end=" ")
print()
print(list(range(4, 1)), len(range(5, 20, 5)))Write the numbers of each range on paper: start, then keep adding the step, and stop before the stop value.
range(4, 1) has no negative step, so it cannot get from 4 to 1. len() of a range counts its numbers.
It prints
2 5 8 3 2 1 [] 3
range(4, 1) is empty. range(5, 20, 5) is 5, 10, 15.
for i in range(2, 11, 3):
print(i, end=" ")
print()
for i in range(3, 0, -1):
print(i, end=" ")
print()
print(list(range(4, 1)), len(range(5, 20, 5)))Output
2 5 8 3 2 1 [] 3
Predict the output
word = "level"
count = 0
for ch in word:
if ch == "l":
count += 1
else:
count += 10
print(count)The loop makes one pass for each of the five characters of the word.
Count how many characters are l and how many are not. Each kind adds a different amount.
It prints
32
Two ls add 1 each; the other three characters add 10 each.
word = "level"
count = 0
for ch in word:
if ch == "l":
count += 1
else:
count += 10
print(count)Output
32
Predict the output
result = ""
for ch in "abc":
result = ch + result + ch
print(result)On every pass the character is put at the front and also at the end.
Trace it: write the value of result after the first pass, then after the second, then after the third.
It prints
cbaabc
Each character is added at both ends: aa, then baab, then cbaabc.
result = ""
for ch in "abc":
result = ch + result + ch
print(result)Output
cbaabc
Predict the output
total = 0
for i in range(1, 8):
if i % 2 == 0:
continue
if i > 5:
break
total += i
print(total, i)continue skips the even numbers. break ends the loop at the first odd number above 5.
After a break, the loop variable keeps the value it had on that pass.
It prints
9 7
1, 3 and 5 are added. 7 is odd and above 5, so the loop breaks with i equal to 7.
total = 0
for i in range(1, 8):
if i % 2 == 0:
continue
if i > 5:
break
total += i
print(total, i)Output
9 7
Predict the output
s = "hello"
for i in range(len(s)):
if i % 2 == 0:
print(s[i].upper(), end="")
else:
print(s[i], end="")
print()i is the position, and s[i] is the character at that position.
Positions 0, 2 and 4 are even, so those characters are printed in capitals. end="" keeps everything on one line.
It prints
HeLlO
s = "hello"
for i in range(len(s)):
if i % 2 == 0:
print(s[i].upper(), end="")
else:
print(s[i], end="")
print()Output
HeLlO
Fix the bug
This should print the numbers 1 to 5. It prints 0 to 4.
The program prints the lines below. Your program must print exactly these lines.
Example run
1 2 3 4 5
Output
range(5) starts at 0 and stops before 5.
Give range two arguments: where to start, and one past the last number you want.
for i in range(1, 6):
print(i)for i in range(1, 6):
print(i)Output
1 2 3 4 5
Fix the bug
This crashes.
Print each letter on its own line.
The program prints the lines below. Your program must print exactly these lines.
Example run
p y t h o n
Output
Read the last line of the error message. len(word) is one number, and a number has no items to step through.
Loop over the word itself, or over range(len(word)).
word = "python"
for letter in word:
print(letter)len(word) is a number, which is not iterable. Loop over the word itself (or over range(len(word))).
word = "python"
for letter in word:
print(letter, end=" ")
print()Output
p y t h o n
Fix the bug
This should count down from 5 to 1. It prints nothing.
Print each number on its own line.
The program prints the lines below. Your program must print exactly these lines.
Example run
5 4 3 2 1
Output
Without a step, range counts up by 1. Can it get from 5 to 0 by counting up?
Give a third argument: a negative step.
for i in range(5, 0, -1):
print(i)Counting down needs a negative step.
for i in range(5, 0, -1):
print(i, end=" ")
print()Output
5 4 3 2 1
Fix the bug
This should print each pair of neighbouring letters. It crashes on the last pass.
Print each pair on its own line.
The program prints the lines below. Your program must print exactly these lines.
Example run
ch ha ai in
Output
On the last pass, i is the last index. What is i + 1 then?
A loop that looks one place forward must stop one pass earlier.
word = "chain"
for i in range(len(word) - 1):
print(word[i] + word[i + 1])On the last pass, i + 1 is past the end. Stop one earlier.
word = "chain"
for i in range(len(word) - 1):
print(word[i] + word[i + 1], end=" ")
print()Output
ch ha ai in
Fix the bug
This should print how many digits are in the text, which is 4. It prints 1.
The program prints the lines below. Your program must print exactly these lines.
Example run
4
Output
Look at where digits = 0 is. How many times does that line run?
Create the counter one time, before the loop starts.
text = "Room 12, floor 34"
digits = 0
for ch in text:
if ch.isdigit():
digits += 1
print(digits)The counter is reset on every pass. Create it before the loop.
text = "Room 12, floor 34"
digits = 0
for ch in text:
if ch.isdigit():
digits += 1
print(digits)Output
4
Fix the bug
This should print only the first vowel in the word. It prints all of them.
The program prints the lines below. Your program must print exactly these lines.
Example run
First vowel: e
Output
After the first vowel is found, the loop keeps going to the next characters.
Which statement leaves a loop at once? Put it after the print line, inside the if block.
word = "education"
for ch in word:
if ch in "aeiou":
print("First vowel:", ch)
breakLeave the loop after the first match.
word = "education"
for ch in word:
if ch in "aeiou":
print("First vowel:", ch)
breakOutput
First vowel: e
Write code · Easy
Squares. Print the squares of the numbers from 1 to 10 on one line.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
1 4 9 16 25 36 49 64 81 100
Output
range(1, 11) gives the numbers 1 to 10.
Print n * n with end=" " so that everything stays on one line.
for n in range(1, 11):
print(n * n, end=" ")
print()for n in range(1, 11):
print(n * n, end=" ")
print()Output
1 4 9 16 25 36 49 64 81 100
Write code · Easy
Spell it out. Ask for a word and print its letters separated by hyphens, in capitals, such as P-Y-T-H-O-N, using a loop. Avoid a hyphen at the end.
Print one line only: the letters in capitals with a hyphen between them.
With the reply python, the program prints the lines below. Your program must print exactly these lines.
Example run
P-Y-T-H-O-N
Output
Build the result in a string that starts empty. Loop over the positions with range(len(word)).
Put the hyphen before every letter except the first one: test i > 0.
word = input("A word: ").upper()
result = ""
for i in range(len(word)):
if i > 0:
result += "-"
result += word[i]
print(result)The hyphen is added before each letter except the first, so there is never one left over at the end.
word = input("A word: ").upper()
result = ""
for i in range(len(word)):
if i > 0:
result += "-"
result += word[i]
print(result)Output
A word: python P-Y-T-H-O-N
The one-line version is "-".join(word).
Write code · Easy
Sum of the evens. Print the sum of all even numbers from 2 to 100, using a range with a step.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
2550
Output
range(2, 101, 2) gives 2, 4, 6 and so on. Why is the stop value 101 and not 100?
Create total = 0 before the loop and add each number to it inside the loop.
total = 0
for n in range(2, 101, 2):
total += n
print(total)total = 0
for n in range(2, 101, 2):
total += n
print(total)Output
2550
Write code · Medium
Count the kinds. Ask for a sentence and print how many letters, digits, spaces and other characters it contains.
Print the four counts in this order: letters, digits, spaces, others.
With the reply Flight 815 lands at 4:30!, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Letters: 13, digits: 6, spaces: 4, others: 2
Output
Create four counters before the loop, all starting at 0.
Inside the loop, use one if/elif/else chain with isalpha(), isdigit() and == " ".
sentence = input("Sentence: ")
letters = digits = spaces = others = 0
for ch in sentence:
if ch.isalpha():
letters += 1
elif ch.isdigit():
digits += 1
elif ch == " ":
spaces += 1
else:
others += 1
print(f"Letters: {letters}, digits: {digits}, spaces: {spaces}, others: {others}")sentence = input("Sentence: ")
letters = digits = spaces = others = 0
for ch in sentence:
if ch.isalpha():
letters += 1
elif ch.isdigit():
digits += 1
elif ch == " ":
spaces += 1
else:
others += 1
print(f"Letters: {letters}, digits: {digits}, spaces: {spaces}, others: {others}")Output
Sentence: Flight 815 lands at 4:30! Letters: 13, digits: 6, spaces: 4, others: 2
letters = digits = spaces = others = 0 gives all four names the starting value 0 in one line (Chapter 3).
Write code · Medium
Factorial table. Print the factorial of every number from 1 to 10, one per line, such as 5! = 120. Use a single loop: each factorial is the previous one multiplied by the next number.
Print ten lines in exactly this form: 5! = 120.
The program prints the lines below. Your program must print exactly these lines.
Example run
1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800
Output
Create factorial = 1 before the loop. Do not reset it inside the loop.
On each pass, multiply the factorial by the loop number, then print the line with an f-string.
factorial = 1
for n in range(1, 11):
factorial *= n
print(f"{n}! = {factorial}")The accumulator is not reset: it carries each factorial into the next pass.
factorial = 1
for n in range(1, 11):
factorial *= n
print(f"{n}! = {factorial}")Output
1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800
Write code · Medium
Divisors. Ask for a positive whole number and print all its divisors on one line, and then how many there are.
Print the divisors first, on one line, from the smallest to the largest. Then print how many there are.
With the reply 36, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
1 2 3 4 6 9 12 18 36 Number of divisors: 9
Output
Try every number from 1 to n. To include n, the stop value is n + 1.
n % d == 0 is true when d divides n exactly. Count each one as you print it.
n = int(input("A positive whole number: "))
count = 0
for d in range(1, n + 1):
if n % d == 0:
print(d, end=" ")
count += 1
print()
print("Number of divisors:", count)n = int(input("A positive whole number: "))
count = 0
for d in range(1, n + 1):
if n % d == 0:
print(d, end=" ")
count += 1
print()
print("Number of divisors:", count)Output
A positive whole number: 36 1 2 3 4 6 9 12 18 36 Number of divisors: 9
Write code · Medium
Decode. The message wkh fdnh lv d olh was encoded with the method in section 14.4, using a shift of 3. Write a loop to decode it.
Print one line only: the decoded message.
The program prints the lines below. Your program must print exactly these lines.
Example run
the cake is a lie
Output
Copy the loop from section 14.4 and change the direction of the shift.
Only letters are shifted. Every other character is copied unchanged.
secret = "wkh fdnh lv d olh"
message = ""
for ch in secret:
if ch.isalpha():
position = ord(ch) - ord("a")
message += chr(ord("a") + (position - 3) % 26)
else:
message += ch
print(message)Decoding is encoding with the opposite shift. % 26 handles the wrap-around in this direction too, because Python's % never gives a negative result for a positive divisor (Chapter 4).
secret = "wkh fdnh lv d olh"
message = ""
for ch in secret:
if ch.isalpha():
position = ord(ch) - ord("a")
message += chr(ord("a") + (position - 3) % 26)
else:
message += ch
print(message)Output
the cake is a lie
Write code · Hard
Longest run. Ask for a string and print the length of the longest run of the same character in a row. For aabbbbcc the answer is 4.
With the reply aabbbbcc, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Longest run: 4
Output
Loop over the positions. When a character equals the one before it, the current run grows by 1. Otherwise a new run starts at 1.
keep a "current run" counter and a "best so far". Compare each character with the one before it.
text = input("Text: ")
best = 0
current = 0
for i in range(len(text)):
if i > 0 and text[i] == text[i - 1]:
current += 1
else:
current = 1
if current > best:
best = current
print("Longest run:", best)The loop starts at index 1, so that each character can be compared with the one before it.
text = input("Text: ")
best = 0
current = 0
for i in range(len(text)):
if i > 0 and text[i] == text[i - 1]:
current += 1
else:
current = 1
if current > best:
best = current
print("Longest run:", best)Output
Text: aabbbbcc Longest run: 4
When the character matches the previous one, the current run grows. Otherwise a new run starts at 1. For an empty string the loop never runs and the answer is correctly 0.
Write code · Hard
Binary to decimal. Ask for a binary number as text, such as 1011, and convert it to decimal with a loop, without using int(text, 2).
With the reply 1011, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
11
Output
Each digit is one character of text. Convert it with int() before you add it.
go through the digits from left to right. For each one, double the total so far and add the digit.
bits = input("Binary number: ")
value = 0
for bit in bits:
value = value * 2 + int(bit)
print(value)bits = input("Binary number: ")
value = 0
for bit in bits:
value = value * 2 + int(bit)
print(value)Output
Binary number: 1011 11
| Pass | bit |
value after |
|---|---|---|
| 1 | 1 |
0 × 2 + 1 = 1 |
| 2 | 0 |
1 × 2 + 0 = 2 |
| 3 | 1 |
2 × 2 + 1 = 5 |
| 4 | 1 |
5 × 2 + 1 = 11 |
Doubling shifts everything one binary place to the left, exactly as * 10 did for decimal digits when reversing a number in Chapter 13.
Write code · Hard
Fibonacci. In the Fibonacci sequence, each number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13... Ask how many numbers to print, and print that many.
Print the numbers on one line, starting with 0.
With the reply 10, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
0 1 1 2 3 5 8 13 21 34
Output
The loop only needs to repeat the given number of times, so for _ in range(count): is enough.
keep two variables for the last two numbers and update both in one line with multiple assignment.
count = int(input("How many Fibonacci numbers? "))
current, following = 0, 1
for _ in range(count):
print(current, end=" ")
current, following = following, current + following
print()count = int(input("How many Fibonacci numbers? "))
current, following = 0, 1
for _ in range(count):
print(current, end=" ")
current, following = following, current + following
print()Output
How many Fibonacci numbers? 10 0 1 1 2 3 5 8 13 21 34
The multiple assignment works out both new values from the old ones before storing either. Written as two separate lines, the first assignment would spoil the value the second one needs.
Project
A report for a step counter. Leo writes down how many steps he walks each day. Write a program that:
for loop and rangeThen print three lines, in this order:
Plan before you write code: you need one accumulator for the sum, a "best so far" with its day number, and one counter.
With the replies 3 then 5000 then 9200 then 8000, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Total steps: 22200 Best day: 2 Days on target: 2
Output
range(1, days + 1) gives the day numbers 1, 2, 3 and so on, with the last day included. Ask for the steps inside the loop.
Create total, best, best_day and on_target before the loop. On each pass, add the steps to the total and compare them with the best so far.
When the steps are greater than the best so far, store both the steps and the day number. Use > and not >=, so that the earlier day wins when two days are equal.
days = int(input("How many days? "))
total = 0
best = 0
best_day = 0
on_target = 0
for day in range(1, days + 1):
steps = int(input(f"Steps on day {day}: "))
total += steps
if steps > best:
best = steps
best_day = day
if steps >= 8000:
on_target += 1
print("Total steps:", total)
print("Best day:", best_day)
print("Days on target:", on_target)One loop collects everything: a sum, a best so far and a count. The code after the loop only prints what the loop collected.