16.7. Using a Negative Change Value with Range¶
range(start, end, change) function can have 3 parameters: the
end, and the amount to
change by. It returns a list that begins with the
start value and generates the rest of the list items by adding the
change value to the
start value. It stops generating the list when the current value is equal or greater than the
end value. So the generated list includes the
start value and excludes the
end value. We have mostly used the
range function to create an increasing sequence of numbers like [0, 1, 2, 3, 4, 5]. But, it can also be used to create a decreasing sequence like [5, 4, 3, 2, 1, 0] as shown below. Remember that the second number to the range function says when to stop and that number is not included in the returned list of numbers.
Here’s a program we saw earlier, but with the
range function parameters changed to create a decreasing list from the last valid index (the length of the list minus 1) to 0.
Can you figure out what the following program does?
source = "United States of America" slowly = "" for index in range(len(source)-1,-1,-1): slowly = slowly + source[index] print(slowly)
Try to figure out what the program above does, then try to answer this question.
Write code to count down by 2 from 10 to 0.
Discuss topics in this section with classmates.