简体   繁体   中英

please help in this reverse range loop exercise not sure why the stop value is -1, shoudn't it be 0 in this start,stop,step range reverse exercise

string = input("Enter a string: ")

for i in range(len(string)-1, -1, -1):
    print(string[i], end="")

I am confused in this start,stop, step not sure why it is -1 in the stop bit I tried putting 0 .

The range function generates a sequence of number from the first value ( start ) to the second one ( stop ) you give it. As the documentation of the stop parameter states:

Required. An integer number specifying at which position to stop (not included).

Therefore, being stop not included in the sequence, if you put 0 there you obtain values from len(string)-1 to 1, with the first character of the string you are iterating (the one at index 0) that will not be reached from the for loop.

So you usually put the next value to the one you are interested in (in this case -1 to iterate until 0).

range(start, stop, step)

start: It is optional. default value is 0.
stop: It is required although the number defined in stop is not included [exclusive]
step: It is optional. default value is 1 

for i in range(len(string)-1, -1, -1): This will iterate from last character to first character

for i in range(len(string)-1, 0, -1): This will iterate from last character to second character

For better understanding:

Ex- range(1,5)  -> 1,2,3,4         #5 is not included.
Ex- range(-9,-5) -> -9,-8,-7,-6    #-5 is not included.
Ex- range(8,3,-1) -> 8,7,6,5,4     #3 is not included.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM