[英]How does a recursive function work in the example below?
def my_func(num):
if num ==0:
return
else:
print(num)
my_func(num-1)
print("The function is called recursively for",(num),"times")
my_func(7)
结果:
7
6
5
4
3
2
1
The function is called recursively for 1 times
The function is called recursively for 2 times
The function is called recursively for 3 times
The function is called recursively for 4 times
The function is called recursively for 5 times
The function is called recursively for 6 times
The function is called recursively for 7 times
我可以理解打印的数字 1 到 7,但为什么报表中的数字从“1 倍”增加到“7 倍”? 一旦 num = 0 不是 function “返回”意味着它不会脱离 function 吗? 为什么它一直打印语句 1 到 7,为什么数字在增加? 当它达到 num = 0 时,我会认为它会脱离 function 并且永远不会到达打印命令?
本质上,这就是您的代码的工作方式:请注意,缩进用于显示它正在运行的“功能”。
my_func(7)
- print 7
- my_func(6)
- print 6
- my_func(5)
- print 5
- my_func(4)
- print 4
- my_func(3)
- print 3
- my_func(2)
- print 2
- my_func(1)
- print 1
- my_func(0)
- return
- print "Called... 1"
- print "Called... 2"
- print "Called... 3"
- print "Called... 4"
- print "Called... 5"
- print "Called... 6"
- print "Called... 7"
Finished everything
但是,在最后的打印语句之间不应该有任何东西,就像 juanpa.arrivillaga 所说的那样。
递归函数是有效嵌套的,因此您的打印行调用print(num)
为 7,然后 function 再次以 6 开始,因此您的print(num)
再次被调用为 6。
一旦达到 0,就会为每个 function 调用底部语句,因为它们是递归完成的。
所以你对于 num = 3,你有效地得到:
my_func(3)
if 3 == 0:
return
else:
print(3)
if 2 == 0:
return
else:
print(2)
if 1 == 0:
return
else:
print(1)
if 0 == 0:
return
print("The function is called recursively for",(1),"times")
print("The function is called recursively for",(2),"times")
print("The function is called recursively for",(3),"times")
# end of outer-most function
我没有在每行之间打印出单独的递增数字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.