for and range() · Python from Zero
How do you repeat code for a range of numbers, or for each letter?
Course contentsWhy 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, 5range(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 afterDefinition
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
Squares
Try it yourselfChange range(1, 6) to range(1, 11).
for i in range(1, 6):
print(i, i * i)- L1i takes the values 1, 2, 3, 4, 5.
i = 1 - L2Each round prints i and its square.
1 1 - L2...last round: i = 5.
5 25
Adding 1 to 100
Try it yourselfThe accumulator total grows each round.
total = 0
for n in range(1, 101):
total = total + n
print(total)- L1Start the accumulator at 0, before the loop.
total = 0 - L3n = 1: total becomes 1.
total = 1 - L3n = 2: total becomes 3. n = 3: 6...
total = 3 - 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)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)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.
- PredictTwo columns
Type exactly what this program prints.
- ModifyProduct instead of sum
This program adds 1 to n. Change it to multiply 1 × 2 × ... × n (the factorial) and print the result.
- 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
| Term | Chinese | Definition |
|---|---|---|
| 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. |