[英]Python function always returning none
The following function returns none instead of 1 at the base case, why is this?以下 function 在基本情况下返回 none 而不是 1,这是为什么呢?
def test(num):
if(num == 1):
print('our num is:',num)
return num
else:
print(num)
num -= 1
test(num)
print(test(5))
Because you're not returning anything under the else.因为你没有在 else 下返回任何东西。 See the below code as a fix.
请参阅下面的代码作为修复。
def test(num):
if(num == 1):
print('our num is:',num)
else:
print(num)
num -= 1
test(num)
return num
print(test(5))
You just forgot to return num
to fix it:您只是忘记返回
num
来修复它:
def test(num):
if(num == 1):
print('our num is:',num)
return num
else:
print(num)
num -= 1
return test(num)
then running print(test(5))
will return 1.然后运行
print(test(5))
将返回 1。
Actually, it very much returns 1
at the base case.实际上,它在基本情况下非常返回
1
。 The problem is that you don't propagate that up the call stack when returning through all the recursive layers, as in the following graphic where you call it with 3
:问题是当通过所有递归层返回时,您不会将其传播到调用堆栈上,如下图所示,您使用
3
调用它:
Caller
| ^
| |
| (None)
v |
test(3) <-----+
| |
| (None)
| |
+-----> test(2) <-----+
| |
| (1)
| |
+-----> test(1)
In this case:在这种情况下:
test(3)
;test(3)
;test(2)
;test(2)
;test(1)
, which returns 1
to `test(2);test(1)
,返回1
到 `test(2);test(2)
then returns None
to `test(3); test(2)
然后返回None
到 `test(3);test(3)
returns None
to the caller. test(3)
返回None
给调用者。 When you come out of the base case, you've returned 1
.当您摆脱基本情况时,您已经返回
1
。 You then return nothing explicit up to the next layer, which means Python will implicitly return None
.然后,您没有显式返回任何内容到下一层,这意味着 Python 将隐式返回
None
。
The only case in which you'll get 1
out of your current code is if you call the base case directly, with test(1)
.您将从当前代码中获得
1
的唯一情况是,如果您直接使用test(1)
调用基本情况。
Fixing that, and making some readability improvements, would be done thusly (comments are to explain my reasoning for change, they don't belong in the real code):解决这个问题并进行一些可读性改进,将因此完成(评论是为了解释我的更改理由,它们不属于真实代码):
def test(num):
# Handle pathological case of passing in something < 1.
if num <= 1:
# Will always print 1 so not sure why it's needed.
print('our num is:',num)
return num
# No need for else since above if bit returns anyway.
print(num)
return test(num - 1) # just pass (num - 1) directly, and propagate.
You return nothing in else.你什么都不返回。 Try this.
尝试这个。
def test(num):
if(num == 1):
print('our num is:',num)
return num
else:
print(num)
num -= 1
return test(num)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.