REVERSE - what am I doing wrong?


#1



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


I'm hoping someone can explain why my code isn't working. I get the error message "Your code looks a bit off--it threw a "string index out of range" error. "


def reverse(text):
    text_length = len(text)
    new_string = ""
    while text_length > 0:
        new_string += text[text_length]
        text_length -= 1
    return new_string


#2

this line is creating bug!
new_string += text[text_length]

suppose original text is "hilton7755"
Its length is 10.

but if you write this..

x = "hilton7755"
x[len(x)] ...what would it return??
Out of range error


#3

Remember that computers start counting from 0. len() however, starts counting at 1 like humans. So hello has a length of 5 but its max index is 4.

Also

You might want to rethink this as you'll be ignoring the item at index 0.


#4

Thanks, I've got it now.


#5

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