Reverse task , only one letter returned


Why my loop only returns one letter from the end , I was expecting it to go through every single letter and return the full text in backwards, what have I done wrong ?
Thanks for looking.

Here is the code I've used:

def reverse(text):
    while index<len(text):
        index= index + 1
    return letter


at each step of the loop you are changing the value of letter to what ever text[index-1] is thats why you are just getting one letter returned.
I have inserted some print statements in your code to help you debug

def reverse(text):
    while index<len(text):
        index= index + 1
        print "index is now %s"%index
        print "letter is now %s\n"%letter
    return letter

print reverse("code")

Also you need to re-evaluate your code logic. it does not achieve the goal


in each run of the while loop, you overwrite the variable with a letter. But just one letter, each time. You will need to create an empty string/list and then append the letters to the list/string.


Thanks for your assistance , I'll try to rethink the code.


check my code, you will get step by step printed output which will help you understand better if any problems feel free to notify :smile:

def reverse(text):
length = len(text)
i = 2
new = text[length - 1]

while i <= length:
    new = new + text[length - i]
    i += 1
    print new
return new


The new above loop is for initialization so dont worry about that the actual working is inside the loop .
If satisfied mark a solution. :wink:


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