"Reverse" exercise


#1



Hello! This is my first time posting to the Q&A forum so please let me know I'm breaking any etiquette -- I did my best to ask my question clearly.

I'm working on the exercise "Reverse" (Python --> Practice Makes Perfect --> Reverse)
https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/1?curriculum_id=4f89dab3d788890003000096#

My question is : Why my code producing the following error message? When I call the function on a string, it correctly produces the string in reverse (e.g. "rhino" becomes "onihr") but I'm still getting the error message below:


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


def reverse(text):
    x = len(text) - 1
    for char in text:
        print text[x],
        x -= 1

Thank you for any help!


#2

You have to "save" your "results" , and also "return" it to see it.


#3

WHAT THE...

That is the exact same problem I have.

Here's my code. could someone help me?

def reverse(text):
length = len(text) - 1
for char in text:
print text[length],
length -= 1

I also have another question: How do you get rid of the space when you call the function?
Would be great if you could help me. Thx!

:smiley:


#4

It's always helpful, and there was a lesson about that, to 'debug' things.
By debug you may consider using a lot of print's and executing function in real.

I've added to your code 2 more lines at bottom which gives you some info about output from function:

def reverse(text):
    length = len(text) - 1
    for char in text:
        print text[length],
        length -= 1

text = raw_input('text for function: ')
print reverse(text)

to get rid off spaces in output you should at the end return a string. Otherwise it will be impossible.
In current shape of your, epiccoolness and lizberg, code there is no returing of function output, and you're not storying what you get by every run of the loop - as kinsz89 mentioned.


#5

but how to remove spaces ...??


#6

i found a way to do it by list...

def reverse(text):
result=[]
length = len(text) - 1
for char in text:
result.append(text[length]),
length -= 1
s=''.join(result)
return s


#8

I did something very similar to this. Though you don't need the for loop the way you did it. If you notice in your loop you never once used the variable char, so you're just adding lines to your code.


#9

Ha! got it! Thanks for all the feedback. Okay I don't want to post the answer, but my code is 8 lines long & I used a list, then I joined the items in the list at the end.

One last question: is there any way to solve this without making a list? Thanks wonderful Codecademy community :smiley:

Edit: Just figured out how to create an emptying string & then add to it. I'm all set. Thanks!