Reverse


#1



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


i wrote the code outside a function and it worked but gave me an error asking where the function was. So i turned it into a function and it says it doesn't work...


#def reverse(text):
text = raw_input(' Enter a string: ')
text_reversed = []
    
i = len(text) - 1
while i >= 0:
    text_reversed.append(text[i])
    i -= 1
        
makeitstring = "".join(map(str, text_reversed))
print makeitstring.


#2

Please include a link to the exercise. Thanks.


#3

map is not needed here. text_reversed is already a list. Note that the list is of strings.


def reverse(x):
    text = []
    n = len(x)
    while n > 0:
        n -= 1
        text.append(x[n])
    return ''.join(text)

print reverse('Python!')    # !nohtyP

#4

Link added. I appreciate it.


#5

Thanks but i have a follow up question.

Wouldn't you want

n = len(x) - 1 (n = len(x) would skip last character)

and

the loop to go from until n >= 0 (n > 0 would skip first character)

since the the index starts at 0?


#6

If you examine my code I subtract 1 from n before referencing that index. As we can see from the result, it works as expected. No characters are skipped. We do indeed reach index 0.


#7

I see. Thanks for your help!


#9

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