7. reverse


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/1/1?curriculum_id=4f89dab3d788890003000096#


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):
    n=""
    for i in range(0, len(text)-1):
        n=n+text[len(text)-i]
    return n


#2

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.


#3

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

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


#4

Thank you!!! That solved it!


#5

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

def reverse(text):
output=[]
print len(text)
letter=0
for char in text:
output.append(text[int((len(text)-1-letter))])
letter+=1
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?


#7

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


#8

"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.


#9

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


#10

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


#11

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