Course outline · 0% complete

0/27 lessons0%

Course overview →

The for loop

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

Quiz

Warm-up from lesson 4-3: with score = 85, which branch runs? if score >= 90: print("A") elif score >= 80: print("B") else: print("C")

Don't repeat yourself, loop

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)

Output: 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, same indentation rule as if from lesson 4-2

Each run of the body is called an iteration. i is a normal variable (unit 3), it just gets reassigned automatically each iteration.

range can also take a start: range(1, 4) gives 1, 2, 3 (again stopping before the end).

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.

Code exercise · python

Run both loops. Notice range(5) starts at 0, while range(1, 4) starts at 1 and stops before 4.

Code exercise · python

Your turn. Use one for loop with range to print the numbers 1 through 10, one per line.