0

So I found a strange thing that happens in python whenever I try to return an optional parameter or at least I think that is why it is happening.

Here is my code

def reverse(string, output = ""):
    if string == "":
        print "winner: ", output
        return output
    output = output + string[-1]
    string = string[:-1]
    reverse(string, output=output)

And here is what happens when I run it:

>>> output = reverse("hello")
winner:  olleh
>>> print output
None

Anyone know why my return is always None?

1
  • Your function has no return value for anything other than the input "" Commented Aug 12, 2015 at 23:31

2 Answers 2

2

You have to return the return value of the recursive call.

def reverse(string, output = ""):
    if string == "":
        print "winner: ", output
        return output
    output = output + string[-1]
    string = string[:-1]
    return reverse(string, output=output)
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh I didn't think about having to go back out of my recursion with the return statement. It makes sense though. Thanks.
0
def reverse(string, output = ""):
    if string == "":
        print ("winner: ", output)
        return output
    output = output + string[-1]
    string = string[:-1]
    return reverse(string, output=output)
def main():
    reverse("hello")
main()

OR

def reverse(string, output = ""):
    if string == "":
        print ("winner: ", output)
        return output
    output = output + string[-1]
    string = string[:-1]
    return reverse(string, output=output)
reverse("hello")

OUTPUT FOR BOTH

>>> 
winner:  olleh
>>> ================================ RESTART ================================
>>> 
winner:  olleh
>>> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.