Reverse task , only one letter returned


#1

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):
    index=0
    while index<len(text):
        index= index + 1
        letter=text[index-1]
    return letter

#2

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):
    index=0
    while index<len(text):
        index= index + 1
        print "index is now %s"%index
        
        letter=text[index-1]
        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


#3

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.


#4

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


#6

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

reverse('Python!')

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:


#7

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