7. Reverse / range question


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/1/1?curriculum_id=4f89dab3d788890003000096


Oops, try again. Your code looks a bit off--it threw a "string index out of range" error. Check the Hint if you need help!


Hi,
I try to solve 7. reverse. but I stuck with function range()

why {for i in range(len(text) -1, -1, -1):} is correct instead {for i in range(len(text), 0, -1):} ?
I know about range function as (start, stop, step).
there is any misunderstand?

Thanks for attention :slight_smile:


def reverse(text):
    new_text = "" # variable for contain reversed text
    for i in range(len(text), 0, -1): # start from text lenth to 0
        new_text = new_text + text[i]
    return new_text


#2

Hi @byteblaster30191,
In fact in range(start, stop, step), the start is inclusive and the stop is exclusive... Ie, the loop will start form start but will end at stop - 1... It will not reach the stop value


#3

if i have the following string: "hello", the length is 5 but strings are zero indexed based, so the indexes are: 0, 1, 2, 3 and 4

that is why you need to do len() - 1


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.