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)的迭代过程可以表示为:
return之前要执行的。
给你举个简单例子
def add(a, b):这个例子很简单,但是说明了函数return之前要执行a+b这个操作
a+b也可以当做一个函数
在复杂一点
def multi(a, b):同样这里在add函数中, 执行return之前,要先把a+mulit(a,b )在返回
如果这就是你迷惑的地方,那就选我把- -~
比如说fact(5)return 返回120点值 为什么不是返回5*4的值?
追答这就是递归啦。
你要求fact(5) 先求fact(4)
你有两个return,当n>1 的时候会一直递归下去
你的递归终止条件是 n ==1 。
这些概念性质的东西 要多看书哦