for Loops and Ranges
A for loop repeats a block once for each item in a sequence.
The square brackets below create a list: an ordered group of values. Lists get a full chapter later; for now, read the values from left to right.
Output:
1
2
3
The name number refers to one item at a time.
Loop Variables
In this loop:
token first refers to "A", then "B", then "C".
The name is ordinary. You choose it. Use a name that describes one item.
range()
range() creates a sequence of integers:
Output:
0
1
2
3
range(4) starts at 0 and stops before 4.
This is one of the first places Python's zero-based counting matters.
range stops before the end
range(4) gives 0, 1, 2, 3.
Ready to run.
range(start, stop)
You can give a start and stop:
Output:
2
3
4
It starts at 2 and stops before 5.
Range Stops Before the End
Do not expect range(1, 5) to include 5:
The output ends at 4.
What is the last number printed by this loop?
Compute it first, then check your number.
HintWrite the range values
range(5) begins at zero and excludes five.
SolutionThe last number is four
range(5) produces 0, 1, 2, 3, 4. The loop therefore prints 4 last.
For Loops Follow a Known Sequence
Use for when you know the collection or range you want to iterate over. The
loop variable is one item at a time.