PMP: 7. Reverse "string index out of range"

def reverse(text):
    TextReverse = ""
    Letter = len(text)
    while Letter > 1:
        TextReverse += text[Letter]
        Letter -= 1
    return TextReverse

Hi all thanks for looking, could someone please point me in the right direction as I am lost, I appreciate people like to just correct the code but if you could also explain why that would be splendid =)

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):
    TextReverse = ""
    Letter = len(text)
    while Letter > 0:
        TextReverse += text[Letter-1]
        Letter -= 1
    return TextReverse

I got this to work with the above code, I don't fully understand why, would still appreciate an explanation


Remember that indexes are not the same as length.
For example let's take "LETTER".
The index for letter are this:
0 1 2 3 4 5

the length of letter len("LETTER") is 6 though

so if you make a function starting to print letter from the end and you use the length of the letter, in this case 6.
You will get an error since there is no letter at index 6. What you want to do is subtract one from it so you actually start at the end.
This is why your text[Letter] didn't work, because you tried to start at an index without any value which as a result was out of range.

Now you can figure the rest out with this.


Thanks mega, this has cleared it up for me and made me realise how silly I was!

I have realised that I basically forgot the whole point of the function and the fact that Letter = len(text) was the starting point when in my head I was telling myself I was starting from 0.

Bit of a derp moment, thanks!


I know that you got your question answered, but just a note on my own personal preference (which may or may not be useful) -

When you create variables, the names should be as functional as the names of defined functions. i.e. - reverse(text) tells you that you are reversing text. Rather than using Letter I would have used length or place so that you don't confuse your goal with the variable (which is what it sounds like happened because letter didn't actually refer to a letter, it was a location at which you would pull the letter)

If that's not helpful, sorry for making you read it!

Good luck!