0

Would anyone be willing to explain why the first does not work, but the second does?

In the first, the function calculates the final, adjusted value...

# returns None
def _pareRotation(degs):
    if degs > 360:          
        _pareRotation(degs - 360)
    else:
        print "returning %s" % degs
        return degs

...but returns None:

print _pareRotation(540)
>> returning 180
>> None

However, if we flip things a bit and return the function...

# returns expected results
def _pareRotation(degs):
    if degs < 360:          
        print "returning %s" % degs     
        return degs
    else:
        return _pareRotation(degs - 360)

...it works as expected:

print _pareRotation(540)
>> returning 180
>> 180

Mostly, wondering what causes that None to get ejected from the recursive loop?

2 Answers 2

4

You're not returning in the first case:

def _pareRotation(degs):
    if degs > 360:          
        _pareRotation(degs - 360)
#      ^
Sign up to request clarification or add additional context in comments.

2 Comments

There should be a canonical question for this if there isn't already. This kind of recursion failure comes up 5 times a day on this tag at least.
Good grief, and there it is. Thank you. I agree @Two-BitAlchemist, but there might be some subtle variance in the questions. I had trouble grokking the idea that the target variable -- let's say final_degs -- would in a sense "become" the recursive function. When I run final_degs = _pareRotation(540), and I print or use final_degs, I'm actually using a variable that has gone through a few transformations (function to int). Is that an accurate way of thinking about it?
0

Yeah, you aren't returning in the first case, and also I think it should be %d, for int.

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.