CodeRigor

LESSON

Repeat steps with for and while

Repeat a block a fixed number of times with for and range, repeat until a condition changes with while, keep counters and running totals, and avoid off-by-one mistakes.

Computers are good at doing the same thing many times without getting bored or making slips. A loop is a statement that runs a block of code repeatedly. Python has two kinds: for, when you know how many times, and while, when you want to carry on until something changes.

for repeats a fixed number of times

Python
for i in range(3):
    print("Hello")
print("Done")

This prints Hello three times and then Done.

The line for i in range(3): means "run the indented block three times". As with if, the first line ends with a colon and the block is indented by four spaces. print("Done") is not indented, so it runs once, after the loop has finished.

Each run of the block is called an iteration.

The loop variable counts from zero

The name after for is a variable. Before each iteration, Python gives it the next number. Print it to see which numbers it gets:

Python
for i in range(3):
    print(i)

This prints 0, 1 and 2, one per line. range(3) produces three numbers, and it starts counting at zero, so the last one is 2, not 3. Counting from zero is normal in programming, and you will get used to it.

When you want different numbers, give range a start and a stop. It starts at the first number and stops before the second.

Python
for number in range(1, 4):
    print(number)

This prints 1, 2 and 3. To count from 1 to 10 you write range(1, 11).

You can name the loop variable anything. i is a common short name for a counter; a descriptive name such as number or day is often clearer.

A running total

A very common pattern: start a variable at zero before the loop, and add to it on every iteration. The variable is called a running total or an accumulator.

Python
total = 0
for number in range(1, 4):
    total = total + number
print(total)

This prints 6, which is 1 + 2 + 3. Step through the diagram to watch number and total change.

A loop variable and a running total
start / 8 ⇄ code
Line 3 runs three times. Each time, number has the next value and total grows by it. Line 4 runs once, after the loop.
A loop variable and a running total
Line 3 runs three times. Each time, number has the next value and total grows by it. Line 4 runs once, after the loop.

The line total = 0 must be before the loop. Inside the block it would run on every iteration and wipe the total each time.

Adding to a variable is so common that Python has a short form. total += number means exactly total = total + number.

Python
count = 0
for i in range(5):
    count += 1
print(count)

This prints 5.

while repeats until a condition becomes false

A while loop has a condition, like if. Python checks the condition; if it is true, it runs the block, then goes back and checks again. The loop ends when the condition is false.

Python
countdown = 3
while countdown > 0:
    print(countdown)
    countdown = countdown - 1
print("Lift off!")

This prints 3, 2, 1 and then Lift off!.

A while loop checks, runs the block, and checks again
start / 3
The condition is tested before every iteration. Something inside the block must change the answer eventually, or the loop never ends.
A while loop checks, runs the block, and checks again
The condition is tested before every iteration. Something inside the block must change the answer eventually, or the loop never ends.

Use while when you cannot say in advance how many iterations there will be. This program keeps asking until the user types the right word. (It reads input, so run it in the Python playground with a few lines of standard input, such as open, please and sesame.)

Python
word = input("Password: ")
while word != "sesame":
    print("Wrong. Try again.")
    word = input("Password: ")
print("Welcome.")

Notice that the block changes word. If nothing in the block could change the condition, the loop would run for ever. That is called an infinite loop. This one never stops, because n stays at 1:

Python
n = 1
while n < 5:
    print(n)

On this site an infinite loop is cut off after a time limit. On your own computer, press Ctrl+C to stop a program that will not finish.

Off-by-one mistakes

A loop that runs one time too many or one time too few has an off-by-one mistake. It is the most common loop bug, and it comes from the edges:

  • range(5) gives 0, 1, 2, 3, 4. Five numbers, but not the number 5.
  • range(1, 5) gives 1, 2, 3, 4. To include 5, write range(1, 6).
  • while n < 5 stops before 5; while n <= 5 includes it.

When you write a loop, check the first value and the last value by hand. Ask: "what is the first number this uses, and what is the last?"

Python
# Meant to print the 3 times table up to 3 x 5.
for n in range(1, 5):
    print(f"3 x {n} = {3 * n}")

This prints four lines and stops at 3 x 4 = 12. The fix is range(1, 6).

Two errors you will meet

A loop block that is not indented.

Python
for i in range(3):
print(i)
Text
  File "main.py", line 2
    print(i)
    ^^^^^
IndentationError: expected an indented block after 'for' statement on line 1

The message names both lines: line 1 has the for, and line 2 is where the indented block should begin. Indent line 2 by four spaces.

Giving range a string. range needs a whole number, and input returns text.

Python
count = "3"
for i in range(count):
    print(i)
Text
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    for i in range(count):
             ~~~~~^^^^^^^
TypeError: 'str' object cannot be interpreted as an integer

Read the last line: something that should be an integer is a str. The marks point at range(count), so count is the string. Convert it where it is read: count = int(input("How many? ")).

What you can do now

You can repeat a block a fixed number of times, use the loop variable, keep a running total, loop until a condition changes, and check a loop's first and last values. In the exercises you will predict what loops print, then write a program that reads several numbers and adds them up.

Next: name a step with a function, and finish a complete program.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

Starts at 'while' (3:24) and continues into 'for' and range: a counter that goes up, the off-by-one mistake, and an accidental infinite loop, all worked through live. Watch to 'Validating Input' (27:00); the later chapters use lists, which this unit does not cover.