Python中递归函数

本文介绍了Python中的递归函数,递归类似于数学归纳法,包含终止条件和递归步骤。文章通过阶乘练习来阐述递归概念,展示了一个计算阶乘的递归函数实现,并给出了计算5的阶乘的结果。

递归函数

​ 递归函数:自己调用自己的函数,在函数体内直接或间接的自己调自己。

#测试递归函数的基本原理。
#test01调test02不会出错,调自己会出现死循环,直到栈满出错。

def test01():
    print("test01")
    test02()

def test02():
    print("test02")

test01()

【结果】

test01
test02

​ 递归类似于数学中的“数学归纳法”。每个递归函数必须包含两个部分:

1、终止条件

​ 表示递归函数什么时候结束,一般用于返回值,不再调用自己。

2、递归步骤

​ 把第n步的值和第n-1步相关联。

递归函数由于会创建大量的函数对象,消耗内存和运算能力。

#递归函数
def test01(n):
    print("test01",n)
    if n==0:
        print("over")
    else:
        test01(n-1)

def test02():
    print("test02")

test01(4)

【结果】

test01 4
test01 3
test01 2
test01 1
test01 0
over

新增一行代码

def test01(n):
    print("test01",n)
    if n==0:
        print("over")
    else:
        test01(n-1)

    print("test01***",n)

def test02():
    print("test02")

test01(4)

【结果】

test01 4
test01 3
test01 2
test01 1
test01 0
over
test01*** 0
test01*** 1
test01*** 2
test01*** 3
test01*** 4

阶乘练习

#递归函数计算阶乘
def factorial(n):


    if n==1:
        return 1
    else:
        return n*factorial(n-1)

result=factorial(5)
print(result)

【结果】

=1:
return 1
else:
return n*factorial(n-1)

result=factorial(5)
print(result)


【结果】

120
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值