Everyone Can Learn Program
中文 Start learning
Course 2 · Python BasicsLesson 9 of 14Free to read

for and range() · Python from Zero

How do you repeat code for a range of numbers, or for each letter?

Course contents

Why you need it

You met for i in range(n) with the robot. In real programs the counter itself is useful: number the lines of a list, add up 1 to 100, go through every character of a word. Combined with a variable that collects a result (an accumulator), loops can calculate things.

The intuition

range gives a sequence of whole numbers:

  • range(5) → 0, 1, 2, 3, 4 (stops before 5)
  • range(1, 6) → 1, 2, 3, 4, 5
  • range(0, 10, 2) → 0, 2, 4, 6, 8 (step 2)

for gives the loop variable each value in turn. It also works on strings: for ch in "abc": gives "a", then "b", then "c".

The accumulator pattern:

total = 0              # start before the loop
for n in range(1, 4):
    total = total + n  # update inside
print(total)           # use after

Definition

range()

range(start, stop, step) produces whole numbers from start up to but not including stop, counting by step.

Accumulator

An accumulator is a variable that is initialised before a loop and updated in each iteration to build up a result.

Examples

Change range(1, 6) to range(1, 11).

for i in range(1, 6):
    print(i, i * i)
Step by step
  1. L1i takes the values 1, 2, 3, 4, 5.i = 1
  2. L2Each round prints i and its square.1 1
  3. L2...last round: i = 5.5 25

Adding 1 to 100

Try it yourself

The accumulator total grows each round.

total = 0
for n in range(1, 101):
    total = total + n
print(total)
Step by step
  1. L1Start the accumulator at 0, before the loop.total = 0
  2. L3n = 1: total becomes 1.total = 1
  3. L3n = 2: total becomes 3. n = 3: 6...total = 3
  4. L4After n = 100 the loop ends; print once.5050

Common mistakes

Resetting inside the loop

If total = 0 is inside the loop, it is reset every round. Initialise accumulators before the loop.

range stops before the end

range(1, 10) stops at 9. To include 10 write range(1, 11).

Quick quiz

1. What does this print?

for i in range(2, 8, 2):
    print(i)
  1. A
    2
    4
    6
  2. B
    2
    4
    6
    8
  3. C
    2
    3
    4
    5
    6
    7
Show the answer

Answer: A

Start at 2, step 2, stop before 8.

2. What does this print?

count = 0
for ch in "hello":
    if ch == "l":
        count = count + 1
print(count)
  1. A
    2
  2. B
    1
  3. C
    5
Show the answer

Answer: A

The loop sees h, e, l, l, o; two of them are "l".

Practice

3 exercises in three steps: predict what a program prints, change a program to meet a new requirement, then write one from scratch. Your code runs in the browser and is checked the moment you submit.

  1. PredictTwo columns

    Type exactly what this program prints.

  2. ModifyProduct instead of sum

    This program adds 1 to n. Change it to multiply 1 × 2 × ... × n (the factorial) and print the result.

  3. WriteCountdown

    Read a whole number n. Print a countdown from n to 1, one number per line, then Go!.

Practise this lesson

Open the interactive lesson to edit and run these examples and solve the exercises with instant feedback. Free to start, no sign-up.

Interactive lessons open in order. If you have not done the earlier ones yet, you start at the course map.

Terms in this lesson

TermChineseDefinition
range()range() 范围函数A function that produces a sequence of whole numbers, stopping before the stop value.
Accumulator累加器A variable set before a loop and updated each round to build a result.
Iteration迭代One pass through the body of a loop.