递归

def countdown(n):
    if n < 0: #base case
        print "the loop is end"
    else:
        print n
        countdown(n - 1)  # call itself
  
countdown(3)

输出:

3

2

1

0

the loop is end 

 

像这样一个函数在函数体内,调用自身,叫做递归调用

这样的处理过程就叫做递归

 

在上面的函数中像 if < 0 的语句算是递归的“出口”,也就是当前函数的终止条件,如果没有类似的代码,函数会一直运行下去。

python 会提示

Runtime Error: maximum recursion depth exceeded。

maxinum一般为1000。

20130716 修订,修订错别字。

posted @ 2013-07-09 16:26  mengfanhao  阅读(153)  评论(0编辑  收藏  举报