Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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.

Checkcountcount > 0Prints
13True3
22True2
31True1
40False(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:

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 25

The 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:

CallValuesHow many
range(5)0, 1, 2, 3, 45
range(2, 8)2, 3, 4, 5, 6, 76
range(1, 10, 2)1, 3, 5, 7, 95
range(10, 0, -2)10, 8, 6, 4, 25
range(5, 5)none0

The rules:

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
p

To 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 10

The 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)
5050

The 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)
33

It 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 529

After 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 stars

The 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
Passitotal after the pass
111
2310
3535

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   9

The 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?

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

BeliefWhat Python doesExample that breaks it
range(1, 10) includes 10It stops just before the stop valuerange(1, 10) ends at 9
A while loop stops the moment its condition becomes falseIt checks only at the top of each passA 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 passThe next pass gets the next value anywayfor i in range(3): with i = 10 inside still prints 0, 1, 2
The loop variable disappears after the loopIt keeps its last valueAfter for i in range(3): pass, i is 2
A while condition says when to stopIt says when to keep goingwhile amount > 1000: with amount = 1 never runs
break ends every loop it is insideIt ends only the innermost loopA break in an inner loop lets the outer loop continue
A nested loop runs its inner block as many times as the outer loopIt multiplies, or adds up the inner passesTwo loops of 1,000 passes run the inner block 1,000,000 times

Summary

Self-check

Answer each question before you open its answer.

  1. 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.

  2. 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. n goes 10, 5, 2, 1, so the block runs three times and the condition is checked four times; the fourth check, 1 > 1, is false.

  3. Write a loop that counts the spaces in the string sentence.

    Answer

    spaces = 0
    for character in sentence:
        if character == " ":
            spaces = spaces + 1

    A counter: start at 0 before the loop, and add 1 inside an if.

  4. 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.

  5. 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 while loop whose condition describes bad input, while len(password) < 8:, with one input before the loop and another inside it, or while True: with a break once len(password) >= 8. A for loop doesn’t fit, because the number of tries isn’t known in advance.

Further reading