python学习-25 函数递归

递归

例如:

def abc(n):
    print(n)
    if int(n/2) == 0:
        return n
    return abc(int(n/2))

abc(10)

运行结果:

10
5
2
1

Process finished with exit code 0

 2.小程序实例

import  time
people_list =['小明','小红','小刚','小王','小青']

def ask(people_list):

    if len(people_list) == 0:
        return '我不知道'

    people = people_list.pop(0)            # 从列表里删除一个人,把值给people

    if people == '小王':
        print('hi %s,我的东西在你那吧' % people)   # 不加这句 会直接跳出下面那句,自我感觉不太好。主要还是看递归的方法吧
        return '%s说:在我家,嘿嘿' % people

    print('hi %s,我的东西在你那吧'%people)
    print('%s说:我不知道,我问一下别人%s'%(people,people_list))
    time.sleep(2)
    res = ask(people_list)
    return res

res = ask(people_list)
print(res)

运行结果:

hi 小明,我的东西在你那吧
小明说:我不知道,我问一下别人['小红', '小刚', '小王', '小青']
hi 小红,我的东西在你那吧
小红说:我不知道,我问一下别人['小刚', '小王', '小青']
hi 小刚,我的东西在你那吧
小刚说:我不知道,我问一下别人['小王', '小青']
hi 小王,我的东西在你那吧
小王说:在我家,嘿嘿

Process finished with exit code 0

 

posted @ 2019-07-04 14:44  学python的菜鸟  阅读(144)  评论(0编辑  收藏  举报