python——函数 26、递归

1、什么是递归?
直接或间接调用函数本身
#直接调用:
def  hello():
    print('ddd')
    hello()
hello()


#间接调用:
def hello():
    print('ddd')
    world()
def world():
    print('yyy')
    hello()
hello()

无论哪种方法都可以从下图看出一个错误 就是不允许无限递归 当一个函数无限的调用时python解释器为了防止你的内存被无限占用所以就会弹出这个错误  必须要有结束条件

递推回溯

# age(1)=age(2)+1
# age(2)=age(3)+1
# age(3)=age(4)+1
# age(4)=age(5)+1
# age(5)=20           
等同于
#age(n)=age(n+1)+1
# age(n)=20



def age(n):
    if n==5:
        return 20
    return age(n+1)+1
x=age(1)
print(x)
原文地址:https://www.cnblogs.com/StevenSunYiwen/p/9453371.html