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 =''
    return l
print reverse("fedcba")


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.


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.


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


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