Course outline · 0% complete

0/27 lessons0%

Course overview →

The for loop

lesson 5-1 · ~11 min · 15/27

Lesson 4-3 covered which branch runs with score = 85.

B, the first condition that is True reading from the top.

Python checks in order: 85 >= 90 is False, then 85 >= 80 is True, so B prints and everything after it is skipped.

Exactly one branch of an if/elif/else chain ever runs, which is the property this unit's loops will build on.

Repeating work without repeating code

Suppose you need to print the numbers 0 through 4. Five print lines would work, but five thousand would not. A loop tells Python to run a block repeatedly.

for i in range(5):
    print(i)

That prints 0, 1, 2, 3, 4, one per line. The pieces:

  • range(5) produces the sequence 0, 1, 2, 3, 4. It starts at 0 and stops before 5, giving exactly 5 numbers
  • for i in ... runs the indented block once per number, and each time the variable i holds the current number
  • The indented block is the loop body, following the same indentation rule as if from lesson 4-2

Each run of the body is called an iteration. i is a normal variable from unit 3, and it just gets reassigned automatically each iteration rather than by a line you wrote.

range can also take a start, so range(1, 4) gives 1, 2, 3, again stopping before the end. The stops-before rule is consistent, and it is the source of most loop off-by-one mistakes.

i01234for i in range(5): the loop body runs once per value
The loop variable i steps through each value range(5) produces, running the body once per value.

Two ranges side by side

range(5) starts at 0, and range(1, 4) starts at 1 and stops before 4.

for i in range(5):
    print(i)
for i in range(1, 4):
    print("Round", i)

Output

0
1
2
3
4
Round 1
Round 2
Round 3

The second loop reuses the comma trick from lesson 1-3 to print a label and a number together, with the space supplied by the comma.

Both loops use i as the loop variable, and the second reassigns it from scratch. Reusing the name is fine because the first loop is completely finished before the second begins, and this is the normal thing to do.

Counting the output lines is a good habit: range(5) gave 5 lines and range(1, 4) gave 3, which is 4 − 1. The count is always the end minus the start.

Counting 1 through 10

To include 10, the range has to stop before 11.

for i in range(1, 11):
    print(i)

Output

1
2
3
4
5
6
7
8
9
10

Reading the pieces

  • range stops one before its second number, so reaching 10 needs range(1, 11). Writing range(1, 10) is the single most common loop mistake in Python, and it prints 1 through 9.
  • The whole program is two lines: the for line ending in a colon, and an indented print(i).
  • The count of iterations is 11 − 1 = 10, matching the ten lines of output. Checking that subtraction before running the code catches the off-by-one every time.