python - 为什么 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”来解决此问题。但这是为什么呢?
解决方案
在这两种情况下,您都需要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]
}
^
推荐阅读
- wordpress - add_meta_box() 输入字段显示在页面顶部
- javascript - 全局定义 Javascript 语言环境
- docker - 在 dockerfile 中处理用户并在其上安装软件包权限被拒绝
- php - 没有变量的php mysql插入查询
- c# - SQL Server 内存中 OLTP 和会话隔离设置为快照的 ASP.NET 会话状态
- c++ - 使用 GMP 获取函数
- go - 恐慌:同步:负 WaitGroup 计数器
- doxygen - Doxygen - 显示不是变量的变量
- python-3.x - 使用代理加载 fetch_lfw_people
- teradata - 在 solaris one liner 中登录 bteq