Reverse - practice make perfect


#1



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


Your code looks a bit off--it threw a "string index out of range" error. Check the Hint if you need help!


def reverse(text):
    x=len(text)
    while x>0:
        print text[x]
        x=x-1


#2

strings are zero index based, so for text="hello" the length will be 5 while the highest index is 4, which is why you get an index error


#3

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

def reverse(text):
    x=len(text)
    while x>0:
        print text[x-1]
        x=x-1

#4

you need to return the reversed string, so just printing each character of string in reversed order won't do.

You will need to have a variable in the end which contains the reversed string so you can return it


#5

i didn't understand :confused:


#6

A post was split to a new topic: Reverse


#7

What do you not understand?


#8

Your function fails on reverse("Python!"). It returns "['!', 'n', 'o', 'h', 't', 'y', 'P']" when it should return "!nohtyP".

def reverse(text):
    x=len(text)-1
    l=[]
    while x>=0:
        l.append(text[x])
        x=x-1
    return l
    for i in l:
        print i,

#9

your function returns a list, it should return a string

you can use .join() to join the list into a string

otherwise you would have to use a loop to concatenate the string, i would recommend .join() though.

Also, a function ends the moment a return keyword is reached, any code after a return keyword won't be executed


#10

Thanx for the helped...

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

#11