Using a Negative Change Value with Range

The range(start, end, change) function can have 3 parameters: the start, 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.

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

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.

You have attempted 1 of 5 activities on this page