7. reverse --I don't get why this works


#1



I'm supposed to reverse the text that goes into the function. I was just trying different things and this worked. I still don't know why it does. Can someone please explain to me how the text that goes in actually gets reversed? Thank you.


def reverse(text):
    answer = ''
    for letter in text:
        answer = letter + answer
    return answer
        
print reverse("abcd")


#2

Look at line4. yeah, the line which starts from answer.
Answer = letter + answer.
It goes like this.
1st step: letter 'a' comes first.(cause it's the first element of array)
and then blank space(' ') comes next.
it becomes 'a '.
2nd step: now the letter is 'b' and answer is 'a '(a with blank space)
letter comes left and answer comes right like this('ba ')
See? it made a input('text') reversed.
variable answer can change because of the line4.
It was just a blank space first. But it changed after line4 implemented.
And the process goes on like the steps I explained above.


#3

I get it. Thank you.


#4

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