7. reverse - It works, but I'm not sure if I understand it completly


This is my code:

def reverse(text):
new_word = ""
for i in range((len(text) -1), -1, -1):
new_word += text[i]
return new_word

print reverse("hello")

At the beginning I was doing it on that way:

def reverse(text):
new_word = ""
for i in range((en(text) , 0, 1):
new_word += text[i]
return new_word

print reverse("hello")

Why doesn't the second code print anything?
Is it because the length says 5 but we have an Index from 0 - 4?
And what about the other -1s?
Is the last one because we wanna count from the last letter to the first?
What about the -1 in the mid?

Not sure if this is right so far :confused:

Thanks for helping me


Well, for starters, you might want fix your typo.


Can you please explain me what do you do there? I don't get it. what is en(text)?


en() is nothing, len() is a built in function which can give you the length of a string


Ok. But if i use the code:

for i in range(len(text), 0, 1):

It doesn't work.
I just wanted to know why I have to write the -1!
Is it because of the Index?


It's because you are trying to go through the index in reverse. by having the -1 you are telling it go in reverse.


Ok! So the -1 at the end tells me to go reverse, doesn't it?
The first and second -1 is just for the Index?


I mean, technically, there's more to it than that. But for all intents and purposes, yes.


range has 3 values:

range(start, stop, step)

so -1 is the step


I think I get it now!
Thanks anyone for the help :slight_smile:


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