Mmm...how exactly?


#1



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


I am not getting this code completely. I know how it works, but I am wondering how the while loop returned all the letters backward. Is it simply how it works? Thanks



def reverse(text):
    l =''
    y=len(text)
    while(y>0):
        l=l+text[y-1]
        y=y-1
    return l
    
print reverse("fedcba")


#2

This is the sort of question that puts us at a disadvantage... How does one create code that works without being able to understand how it works? You see the quandary we face. As it stands, it is a posted solution which breaches our general rule, and if we leave it up we can expect to see it again in someone else's question. I'm going to hide it in a spoiler tag to keep it from being indexed (or copied).

How does it work? First, let's do a quick revision to simplify the code:


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

print (reverse("fedcba"))

`


The above makes it a bit more obvious that length is one more than the last index. Inside the loop we subtract 1 from y, giving that index in the first iteration, hence that letter character. With each successive iteration y is always 1 less than previous, so moving from right to left through the text, and appending each one to the return string. The result is the reverse of what we started with.

#3

Thanks, I had a problem regarding the while loop, which I understood now, thanks as well for putting it in spoiler tag. I didn't know it was available.


#4

Not really the correct language. There is no appending, here. Only reassignment can change a string, meaning it is replaced, not appended. My apologies.


#5

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