Repeating Work with Loops · practice
Choose a Start, Stop, and Step
The previous lesson used one or two range(). A third argument gives you control over the distance between its numbers.
These are the three forms:
range(stop)
range(start, stop)
range(start, stop, step)
start is the first number and defaults to
0;stop is the boundary that is never included;
step is the amount added each time and defaults to
1.
Choose a positive step
This
It produces 0, 5, 10, 15, and 20. Adding five again would reach the excluded stop 25, so the range ends.
The same pattern can count through even numbers:
This prints 2, 4, 6, 8, and 10 on separate lines.
Count backward with a negative step
A negative step makes the numbers decrease:
This range starts at 3, subtracts 1 each time, and stops before 0. It therefore produces 3, 2, and 1.
If the countdown should include zero, move the excluded stop one step farther:
range(3, -1, -1)
That produces 3, 2, 1, and 0.
The direction must agree with the step. A positive step moves toward a larger stop. A negative step moves toward a smaller stop.
If the start is already at or beyond the stop in that direction, the range is empty. For example, range(0), range(4, 4), and range(0, 5, -1) produce no values, so a range(0, 5, 0) raises
What does this code print?
for value in range(10, 0, -3):
print(value)Which call counts down from 5 and includes 0?
Build a stepped range
The loop in the editor currently produces no values. Change only its range() call so it counts from 10 down by threes and produces 10, 7, 4, and 1.
Task
Change the range(0) call.
Start at
10.Stop before
0.Use a step of
-3.Keep the
body and final print(values)line unchanged.
The final [10, 7, 4, 1].