Reverse


#1



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


I get this error message:
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!


def reverse(text):
    a = len(text)
    while a > 0:
        print text[a],
        a -= 1


#2

This is an issue with your array lengths. Since they're zero-based, setting a to be equal to the length of the array causes issues. If your array had 4 items in it, A would be equal to 4. When you try to access text[a], it's looking at text[4], which doesn't exist.

The easiest solution to this would be to change the second line to a = len(text) - 1 so that it checks all the indices properly


#3

Thanks for your reply! I tried that and now I get this error:

Your function fails on reverse("Python!"). It returns "None" when it should return "!nohtyP".


#4

Did you remember to call the function by using reverse("Python!") at the end? I just ran the code and it seems to be working perfectly fine


#5

weird, I did, and it still gives me an error:


#6

I ran the following code over at labs repl.it

def reverse(text):
    a = len(text) -1
    while a >= 0:
        print text[a],
        a -= 1
        
reverse("Python!")

which then returned ! n o h t y P as it’s output. I also needed to change the loop from > to >= to get it to properly return the P. What error are you getting?

I haven’t been able to test it in the actual lesson, since I haven’t unlocked it yet


#7

It prints the following with the same error message:

! n o h t y PNone


#8

alright, I just tested it in my external editor, and there it works perfectly fine. Seems to be an error with the lesson, not an error on my part. Thanks a lot for your help!


#9

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