for loops and range
Trace a for loop over range(start, stop, step) and over a string, giving the values its loop variable takes, and choose for or while for a task.
It opens on
In this loop k takes the values of range(2, 11, 3), adding 3 each time. Will k ever be 11, or is its last value 8, or 10?
Why it matters
Most loops in real programs go through a known set of values (every item of an order, every pixel of a row, every character of a password), and a for loop writes the start, the stop and the step in one line where a while loop spreads them over three.
Good to know first
- while loops: a block repeats and a variable must change
- Variables and assignment: total = total + k reads the old total, then binds total to the new value
- Input, output and type conversion: print shows values separated by a space
Step by step
One line, three numbers
Trace a for loop over range(start, stop, step) and give the values of the loop variable and the total at each pass.
The range starts at 2, so k is 2 on the first pass, and the block makes total 2 and prints 2 2.
A common mix-up
The stop value is included, so k reaches 11.
In fact: a range stops before its stop value, so the last k is 8 and 11 is never reached.
Every shape of range
Write the range that gives a list of values, give the values of a range and count them.
With three numbers the last is the step, so range(1, 10, 4) goes 1, then 5, then 9, and stops there because 13 is past 10.
A common mix-up
Range(5, 0, -1) includes 0, or a range with the start past the stop gives an error.
In fact: The stop is never included, and a range that cannot get from start to stop is simply empty.
Strings, and for or while
Trace a for loop over a string, and choose for or while from whether the values are known before the loop starts.
The second pass has ch equal to "o" and prints oo, and the third has ch equal to "!" and prints !!; then the string has no more characters and the loop ends, with no counter and no index.
A common mix-up
A for loop needs a counter variable and an index to get at each character.
In fact: The loop variable takes each character itself, with no counter.
Try it
For k in range(4, 20, 5) with the same block, what is the last value of k?Answer
19
Hint: 4, 9, 14, 19, and 24 is past the stop
Write a range that gives 12, 9, 6, 3.Answer
Range(12, 0, -3)
Hint: The step is -3, and the stop must be below 3
What does for ch in "hi": print(ch + "!") print?Answer
h! then i!
Hint: One line for each character
Adding 3 again gives the next value of k. What are k and total on the third pass?Answer
k is 8 and total is 15.
What are the values of range(3, 20, 5), and how many are there?Answer
3, 8, 13 and 18, which is four values (23 is past 20).
