python中递归函数的解释

时间:2018-11-21 15:17:41

标签: python recursion

我是python的新手,没有递归的概念。我可以对以下代码进行解释吗?

def rec(k):
    if(k>0):
        print('the value of k is:',k)
        result = k+rec(k-1)
        print(result)
    else:
        result = 0
    return result
rec(8)

输出为:

the value of k is: 8
the value of k is: 7
the value of k is: 6
the value of k is: 5
the value of k is: 4
the value of k is: 3
the value of k is: 2
the value of k is: 1
1
3
6
10
15
21
28
36

每个print(result)之后我们没有得到print('the value of k is',k)怎么办

0 个答案:

没有答案