Why doesn't the code work?


#1

def reverse(texto):
n=1
while n!=(len(texto)-1):
return texto[len(texto)-n]
n+=1

I mean, this counts from n=1 until n=len(text-1) returning the last letter every cicle but only returns the last letter and stops, why?


#2

@lucarien,

1

A return-statement will cause an EXIT

2

the condition of your while-loop is not correct

def reverse(texto):
 n=1
 while n<=(len(texto)):
     print texto[len(texto)-n],
     n+=1
 print ""

reverse("Leo")

#3

Leonhard is on the nose: your return statement tells Python to stop processing.

My personal alternative:

def reverse(text):
    i = len(text)-1
    reverse = ""
    
    while i >= 0:
        reverse = "%s%s" %(reverse, text[i])
        i -= 1
        
    return reverse

In my case, I define an index counter at the length of the string minus 1. I then cycle through this index, counting down to zero so I can grab all elements of the string in reverse, while building a new string.

Leonhard's approach is nicely subtle too, printing as he goes through the elements/chars.


#4

@tsluyter,

def reverse(text):
    i = len(text)-1
    reverse = ""
    while i >= 0:
        reverse = "%s%s" %(reverse, text[i])
        i -= 1
    return reverse

print reverse("Leo")

#5

Yep, don't know why the indention in mine went cooky. Fixed it.


#6

Thanks! I was misusing the return-statment, fixed-it!