首页 > 解决方案 > 为什么 Python 返回 None 而不是 value

问题描述

这些愚蠢的问题中的另一个。我在这里有一个非常简单的算法来计算最大的 commen 分频器。

我的 C++ 片段看起来像这样

int findGcd(int m, int n)
{
    int r = m % n;

    if(r == 0)
    {
        return n;
    }

    else
    {
        m = n;
        n = r;
        findGcd(m, n);
    }
}

int main()
{
    cout << findGcd(13, 3);

    return 0;
}

...它返回(与本例中的预期完全一样)1。

如果我在 Python 中实现它 - 如下所示:

def findGcd(m, n):
"""Calculates the greatest common divider """
    r = m % n

    if r == 0:
        return n

    else:
        m = n
        n = r
        findGcd(m, n)




number = findGcd(13,3)
print(number)

它只是返回 NONE 而不是 1。我已经对其进行了调试,并且 n 确实存储了正确的 1 值,但仍然返回 None。

我可以通过在 else 分支中对函数的递归调用添加“return”来解决此问题。但这是为什么呢?

标签: pythonc++algorithmmath

解决方案


在这两种情况下,您都需要return在递归调用中使用 a。

没有它,在 C++ 中,你有未定义的行为。在 Python 中,你得到None.

C++

int findGcd(int m, int n)
{
    int r = m % n;

    if(r == 0)
    {
        return n;
    }

    else
    {
        m = n;
        n = r;
        return findGcd(m, n);
    }
}

Python:

def findGcd(m, n):
"""Calculates the greatest common divider """
    r = m % n

    if r == 0:
        return n

    else:
        m = n
        n = r
        return findGcd(m, n)

您可以通过提高编译器的警告级别来发现 C++ 中的此类问题。g++ -Wall,我得到:

socc.cc: In function ‘int findGcd(int, int)’:
socc.cc:16:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^

推荐阅读