返回函数或值:递归 python 函数



有人愿意解释为什么第一个不起作用,但第二个不起作用吗?

在第一个中,该函数计算最终的调整值...

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

。但返回None

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

但是,如果我们稍微翻转一下并返回函数......

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

。它按预期工作:

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

大多数情况下,想知道是什么原因导致None从递归循环中弹出?

在第

一种情况下,您不会返回

def _pareRotation(degs):
    if degs > 360:          
        _pareRotation(degs - 360)
#      ^

是的,在第一种情况下你不会返回,而且我认为它应该是 %d,对于 int。

最新更新