递归
例如:
def abc(n):print(n)if int(n/2) == 0:return nreturn abc(int(n/2))abc(10)
运行结果:
10
5
2
1Process 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) # 从列表里删除一个人,把值给peopleif people == '小王':print('hi %s,我的东西在你那吧' % people) # 不加这句 会直接跳出下面那句,自我感觉不太好。主要还是看递归的方法吧return '%s说:在我家,嘿嘿' % peopleprint('hi %s,我的东西在你那吧'%people)print('%s说:我不知道,我问一下别人%s'%(people,people_list))time.sleep(2)res = ask(people_list)return resres = ask(people_list) print(res)
运行结果:
hi 小明,我的东西在你那吧 小明说:我不知道,我问一下别人['小红', '小刚', '小王', '小青'] hi 小红,我的东西在你那吧 小红说:我不知道,我问一下别人['小刚', '小王', '小青'] hi 小刚,我的东西在你那吧 小刚说:我不知道,我问一下别人['小王', '小青'] hi 小王,我的东西在你那吧 小王说:在我家,嘿嘿Process finished with exit code 0