python 递归函数与return

def fact(n):
if n==1:
return 1
return n * fact(n - 1)
return 是怎么把递归函数给返回出来
麻烦对过程详细的说一下

以上的递归函数相当于:


>>> def fact(n):

if n==1:

return 1

else:

return n*fact(n-1)


>>> fact(1)

1

>>> fact(5)

120

>>> 

比如fact(5)的迭代过程可以表示为:

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-08-11

return之前要执行的。

给你举个简单例子

def add(a, b):
    return a + b

这个例子很简单,但是说明了函数return之前要执行a+b这个操作

a+b也可以当做一个函数

在复杂一点

def multi(a, b):
    return a * b

def add(a, b):
    return a + multi(a, b)

同样这里在add函数中, 执行return之前,要先把a+mulit(a,b )在返回

如果这就是你迷惑的地方,那就选我把- -~

追问

比如说fact(5)return 返回120点值 为什么不是返回5*4的值?

追答

这就是递归啦。
你要求fact(5) 先求fact(4)
你有两个return,当n>1 的时候会一直递归下去
你的递归终止条件是 n ==1 。
这些概念性质的东西 要多看书哦

本回答被提问者和网友采纳
第2个回答  2016-08-11
return 就是跳出、返回的意思。
所以没有什么过程,就是从函数、递归里跳出来了。
第3个回答  2016-08-10
fact(1) -> 1

fact(2) -> 2 * fact(1) -> 2 * 1 = 2
fact(3) -> 3 * fact(2) -> 3 * 2 * fact(1) - ? 3 * 2 * 1 = 6
.....
相似回答