我的函数即使在上面一行打印时也不返回None,我缺少什么?

2024-10-01 13:42:05 发布

您现在位置:Python中文网/ 问答频道 /正文

即使我在上面一行打印变量,我的recurusive函数也不会返回None

当我调用函数时,它会精确地打印出我想要的内容,但不返回任何内容

def nRound(vector, root):
    tempRoot = root
    a = vector.pop()
    b = vector.pop()
    if  a+b < 1.0:
        vector.append(a+b)
        rootn = Node(a+b)
        rootn.right = tempRoot
        rootn.left = Node(b)
        nRound(vector, rootn)

    else:    
        rootn = Node(a+b)
        rootn.right = tempRoot
        rootn.left = Node(b) 
        print(rootn)   
        return rootn 

我不明白为什么它返回None而不是rootn。提前谢谢


Tags: 函数rightnonenode内容defrootleft
1条回答
网友
1楼 · 发布于 2024-10-01 13:42:05

您的函数是递归的,只有基本情况返回一个值。递归调用中的值不会向上传递:

    nRound(vector, rootn)

这意味着只有当函数立即到达基本情况时,外部调用方才能获得值。上面的线应该是

    return nRound(vector, rootn)

相关问题 更多 >