[英]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.