Objectives: LO-4.1, LO-4.2, LO-4.3, LO-4.4
Prerequisites: Module 3
Time: about 5.5 hours: 2 for this reading, 2 for Lab 4, and 1.5 for the
practice
A program that adds up 100 numbers shouldn’t need 100 lines. A loop runs the same block of
code again and again, with a different value each time or until something changes. In this
module you learn Python’s two loops, while and for, four patterns that solve most problems
loops are used for, and how to work out, before you run it, what a loop will do and how many
times.
while loops¶
A while loop runs its block for as long as its condition is true:
count = 3
while count > 0:
print(count)
count = count - 1
print("Liftoff!")3
2
1
Liftoff!It looks like an if, and it starts the same way: Python checks the condition, and runs the
indented block if it is true. The difference comes at the end of the block: instead of carrying
on, Python goes back to the top and checks the condition again. Each run of the block is called a
pass (or an iteration). When the condition is false, Python skips the block and carries
on with the first line after it.
Tracing a loop¶
A trace table, from Module 2, shows a loop’s work. Give each pass a row, and include the condition, because the condition decides when the loop stops.
| Check | count | count > 0 | Prints |
|---|---|---|---|
| 1 | 3 | True | 3 |
| 2 | 2 | True | 2 |
| 3 | 1 | True | 1 |
| 4 | 0 | False | (the loop ends) |
The condition is checked four times, and the block runs three times. The condition is checked only at the top of each pass, not in the middle of the block.
Loops that never stop, and loops that never start¶
A while loop stops only when its condition becomes false, so something in the block must change
what the condition depends on. This loop forgets to:
total = 0
n = 1
while n <= 10:
total = total + n
print(total)n stays 1, so n <= 10 stays true, and the loop never ends. The program prints nothing and
never finishes: an infinite loop. To stop it:
In a terminal, press Ctrl+C (on a Mac too). Python stops with a traceback that ends in
KeyboardInterrupt, naming the line it was running.In JupyterLab, click the Interrupt the kernel button, the square (■) in the notebook’s toolbar, or choose Kernel > Interrupt Kernel.
The fix is the missing line, n = n + 1, at the end of the block. Then the loop runs 10 times
and prints 55.
The opposite mistake is a condition that is false from the start, so the block never runs:
amount = 1
while amount > 1000:
amount = amount * 2
print(amount)This prints 1. The condition says when to keep going, not when to stop, and here it should
be amount <= 1000. When a while loop misbehaves, ask two questions: is the condition true at
the start, and does each pass move it toward false?
for loops and range¶
A for loop runs its block once for each value in a sequence, and gives the value a name each
time:
for number in range(1, 6):
print(number, "squared is", number * number)1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25The name after for, here number, is the loop variable. Python makes it refer to the next
value at the start of each pass. You never update it yourself, so a for loop can’t forget to,
which makes it the safer choice whenever you know in advance what to loop over.
range¶
range produces a sequence of whole numbers. It takes one, two, or three values:
| Call | Values | How many |
|---|---|---|
range(5) | 0, 1, 2, 3, 4 | 5 |
range(2, 8) | 2, 3, 4, 5, 6, 7 | 6 |
range(1, 10, 2) | 1, 3, 5, 7, 9 | 5 |
range(10, 0, -2) | 10, 8, 6, 4, 2 | 5 |
range(5, 5) | none | 0 |
The rules:
range(stop)starts at 0.range(start, stop)starts atstart.The
stopvalue is never included.range(2, 8)stops at 7.The third value is the step, the amount added each time, 1 unless you give another. A negative step counts down, and stops just before
stopagain.With a step of 1,
range(start, stop)givesstop - startvalues, so a loop over it runs that many times.range(5)runs 5 times.If
startis already paststop, the range is empty, and a loop over it never runs.
Leaving out the stop value is deliberate: range(n) runs exactly n times, and range(0, 5)
and range(5, 10) fit together with no gap and no overlap.
Looping over a string¶
A for loop over a string gives its characters, one at a time, from the left:
for letter in "loop":
print(letter)l
o
o
pTo ask whether a character is one of several, use in: letter in "aeiou" is True when
letter is a lowercase vowel. (Module 6 does much more with strings and in.)
Printing on one line¶
print ends each line with a newline. Give it end=" " to end with a space instead, so that the
values of a loop print on one line:
for number in range(1, 11, 3):
print(number, end=" ")
print()1 4 7 10The final print() ends the line. (end= is a keyword argument; Module 5 explains them.)
Four loop patterns¶
Most loops follow one of a few patterns. Learn to recognize them, and you can write most loops by choosing a pattern and filling it in.
The accumulator¶
An accumulator is a variable that builds up a result, one pass at a time. Set it up before the loop, update it inside, and use it after:
total = 0
for number in range(1, 101):
total = total + number
print(total)5050The starting value is the result for no passes at all: 0 for a sum, 1 for a product, and "" for
a string built up piece by piece.
The counter¶
A counter is an accumulator that adds 1 each time something is true:
multiples = 0
for number in range(1, 100):
if number % 3 == 0:
multiples = multiples + 1
print(multiples)33It counts the multiples of 3 from 1 to 99: 3, 6, 9, and so on up to 99.
Search with break¶
break ends the loop at once, and Python carries on after it. Use it to stop searching as soon as
you find what you want. Which is the first whole number whose square is more than 500?
for number in range(1, 100):
if number * number > 500:
break
print(number, "squared is", number * number)23 squared is 529After the loop, the loop variable still refers to its last value, which is the one the search
found. If the loop could end without finding anything, the program needs to know which way it
ended; a variable that starts as False and becomes True when the search succeeds, often named
found, tells it.
continue is break’s relative: it skips the rest of the current pass and goes on to the next.
for n in range(1, 11): with if n % 2 == 0: continue before a print(n) prints only the odd
numbers. An if around the print usually says the same thing more plainly.
Input validation¶
A program that asks for input should ask again until the input makes sense. A while loop does
this:
rating = int(input("Rating from 1 to 5: "))
while rating < 1 or rating > 5:
print("Please enter a number from 1 to 5.")
rating = int(input("Rating from 1 to 5: "))
print("Thank you:", rating, "stars")Rating from 1 to 5: 9
Please enter a number from 1 to 5.
Rating from 1 to 5: 0
Please enter a number from 1 to 5.
Rating from 1 to 5: 4
Thank you: 4 starsThe condition describes bad input, and the loop keeps asking while the input is bad. The
input line appears twice, once before the loop and once inside. Another common form starts with
while True:, which is always true, and leaves with break once the input is good:
while True:
rating = int(input("Rating from 1 to 5: "))
if 1 <= rating <= 5:
break
print("Please enter a number from 1 to 5.")Both forms still stop with a ValueError if the user types a word instead of a number. Module 12
shows how to catch that error and ask again.
Tracing a loop’s variables¶
When a loop gives the wrong answer, trace it. Give the table a column for each variable that changes, and a row for each pass. Here is a loop and its trace:
total = 0
for i in range(1, 6, 2):
total = total + i * i| Pass | i | total after the pass |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 3 | 10 |
| 3 | 5 | 35 |
range(1, 6, 2) gives 1, 3, and 5; the next value, 7, is past the stop. The loop makes three
passes, and total ends at 35. Lab 4 has you trace loops like this one, and Python Tutor draws
the same steps.
Nested loops¶
A loop’s block can contain another loop. For each pass of the outer loop, the inner loop runs all the way through:
for row in range(1, 4):
for column in range(1, 4):
print(f"{row * column:4}", end="")
print() 1 2 3
2 4 6
3 6 9The outer loop runs 3 times, and each time the inner loop runs 3 times, so the inner block, the
print of a product, runs 3 × 3 = 9 times. The print() after the inner loop belongs to the
outer loop (look at its indentation), so it runs 3 times and ends each row.
How many times does the inner block run?¶
When the inner loop’s range doesn’t depend on the outer loop, multiply: an outer loop of 4 passes around an inner loop of 5 runs the inner block 4 × 5 = 20 times.
When it does depend on the outer loop, add up the inner loop’s passes for each outer pass. This loop prints a triangle:
for row in range(1, 5): for column in range(row): print("*", end="") print()* ** *** ****The inner loop runs 1, then 2, then 3, then 4 times: 1 + 2 + 3 + 4 = 10 stars in all.
The count matters: a nested loop over 1,000 values in each loop runs its inner block a million times. Module 8 times code, and shows how counts like this turn into waiting.
break in an inner loop ends only the inner loop; the outer loop goes on to its next pass.
Common misconceptions¶
| Belief | What Python does | Example that breaks it |
|---|---|---|
range(1, 10) includes 10 | It stops just before the stop value | range(1, 10) ends at 9 |
A while loop stops the moment its condition becomes false | It checks only at the top of each pass | A pass that makes the condition false still runs to the end of its block |
Changing the loop variable inside a for loop changes the next pass | The next pass gets the next value anyway | for i in range(3): with i = 10 inside still prints 0, 1, 2 |
| The loop variable disappears after the loop | It keeps its last value | After for i in range(3): pass, i is 2 |
A while condition says when to stop | It says when to keep going | while amount > 1000: with amount = 1 never runs |
break ends every loop it is inside | It ends only the innermost loop | A break in an inner loop lets the outer loop continue |
| A nested loop runs its inner block as many times as the outer loop | It multiplies, or adds up the inner passes | Two loops of 1,000 passes run the inner block 1,000,000 times |
Summary¶
A
whileloop runs while its condition is true, checking it at the top of each pass. Make sure each pass moves the condition toward false, and that it is true at the start when the loop should run.A
forloop gives each value of a sequence to its loop variable in turn.range(start, stop, step)never includesstop, andrange(stop)runsstoptimes.The accumulator, the counter, search with
break, and the input-validation loop solve most problems that need a loop.Trace a loop with a row per pass and a column per changing variable.
A nested loop runs its inner block once for each pass of the inner loop in each pass of the outer loop: multiply when the ranges are independent, and add when they aren’t.
Self-check¶
Answer each question before you open its answer.
What values does
range(3, 15, 4)produce, and how many times does a loop over it run?Answer
3, 7, and 11, so three times. The next value, 15, is the stop, which is never included.
What does this print, and how many times is the condition checked?
n = 10 while n > 1: n = n // 2 print(n)Answer
It prints
1.ngoes 10, 5, 2, 1, so the block runs three times and the condition is checked four times; the fourth check,1 > 1, is false.Write a loop that counts the spaces in the string
sentence.Answer
spaces = 0 for character in sentence: if character == " ": spaces = spaces + 1A counter: start at 0 before the loop, and add 1 inside an
if.How many stars does this print?
for row in range(3): for column in range(4): print("*", end="")Answer
12: the outer loop runs 3 times, and the inner loop runs 4 times on each pass.
A program asks for a password until the user types one of 8 or more characters. Which loop and which condition would you use?
Answer
A
whileloop whose condition describes bad input,while len(password) < 8:, with oneinputbefore the loop and another inside it, orwhile True:with abreakoncelen(password) >= 8. Aforloop doesn’t fit, because the number of tries isn’t known in advance.
Further reading¶
The Python Tutorial, sections 4.2 to 4.4, for Statements, The range() Function, and break and continue Statements. The language’s own short introduction to
for,range,break, andcontinue. Section 4.5, which follows, showselseon a loop, which this course doesn’t use.Allen B. Downey, Think Python, 3rd edition, chapter 7, Iteration and Search. Loops over words in a text file, with the counter and search patterns this module teaches.
Al Sweigart, Automate the Boring Stuff with Python, 3rd edition, chapter 3, Loops.
while,for,range,break, andcontinue, then two short programs: a number-guessing game like Lab 4’s, and rock, paper, scissors.Python Tutor. Step through any loop in this module to see each pass and check your trace tables.