为什么在python中递归调用相同的函数时使用return

时间:2022-07-29 21:24:01
def foo(n):
    print(n)
    foo(n-1)
>>foo(5)
>>5


>>1

Function with return

功能与返回

def foo(n):
    print(n)
    return f(n-1)
>>5


>>1

Both these functions yields same result. So is it okay to not use return in such cases?

这两个函数都产生相同的结果。那么在这种情况下不使用返回是否可以?

2 个解决方案

#1


1  

It depends on whether you just want to print your output, or to actually assign it. Just printing it is fine if you just want to see your output, but how would you actually use that output later? You could copy and paste it, but that seems inefficient...

这取决于您是只想打印输出还是实际分配输出。如果您只想查看输出,只需打印它就可以了,但您以后如何实际使用该输出?你可以复制并粘贴它,但这似乎效率低下......

However, in your case, it looks like you just want to see the output of each call in your recursion, in which case, there is no need to assign it.

但是,在您的情况下,看起来您只想查看递归中每个调用的输出,在这种情况下,无需分配它。

#2


0  

In this case in particular it doesn't matter, it's just like making a recursive void function in other programming languages.

在这种情况下,特别是无关紧要,就像在其他编程语言中创建递归void函数一样。

#1


1  

It depends on whether you just want to print your output, or to actually assign it. Just printing it is fine if you just want to see your output, but how would you actually use that output later? You could copy and paste it, but that seems inefficient...

这取决于您是只想打印输出还是实际分配输出。如果您只想查看输出,只需打印它就可以了,但您以后如何实际使用该输出?你可以复制并粘贴它,但这似乎效率低下......

However, in your case, it looks like you just want to see the output of each call in your recursion, in which case, there is no need to assign it.

但是,在您的情况下,看起来您只想查看递归中每个调用的输出,在这种情况下,无需分配它。

#2


0  

In this case in particular it doesn't matter, it's just like making a recursive void function in other programming languages.

在这种情况下,特别是无关紧要,就像在其他编程语言中创建递归void函数一样。