Home > Mobile >  please help in this reverse range loop exercise not sure why the stop value is -1, shoudn't it
please help in this reverse range loop exercise not sure why the stop value is -1, shoudn't it

Time:01-16

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.

CodePudding user response:

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).

CodePudding user response:

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.
  • Related