7. reverse



Hi! Can you please help me understand what is wrong whit this code.

"Oops, try again. Does your reverse function take exactly one argument (a string)? Your code threw a "unsupported operand type(s) for -: 'str' and 'int'" error."

def reverse(text):
    for i in range(0, len(text)-1):
    return n


Is that really the error you're getting? When I run it I get "IndexError: string index out of range", which is a result of how you're pulling in the letters.


There was an error in the len(text) statements used in the loop.
This is how I solved it:

def reverse(text):
for i in range(0, len(text)):
n = n + text[len(text)-1-i]
return n
print reverse("len text")


Thank you!!! That solved it!


Can we talk about this? I probably went the long way around..but I did the following:

def reverse(text):
print len(text)
for char in text:
return "".join(output)

I guess I didn't need to add each letter to a list..since a string is, well, kind of like a list?


this code works perfectly on local python on windows environment and even in codeacademy interface. but i still get error
"Oops, try again. Your function fails on reverse("Python!"). It returns "None" when it should return "!nohtyP".

def reverse(text):
st="" #define empty string
index= len(text) #get length of the string
for i in range(0, index): #loop through the string
st = st + text[(index-1)-i] #append empty string with last character of input string with concatenation
print (st) #print string in reserve order

reverse("Python!") #call function with Python! as input


"Oops, try again. Your function fails on reverse("Python!"). It returns "None" when it should return "!nohtyP".

Your error gives you your problem. You need to return st instead of printing st. It returns "None" because you didn't have it return anything.


SOLVED! i was printing within function instead of returning value. thanks for pointing it out.


I did the same but that is giving the error saying 'int can't be iterated'


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