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 函式不“回傳”意味著它不會退出函式嗎?為什么它一直列印陳述句 1 到 7,為什么數字會增加?當它達到 num = 0 時,我會認為它會退出函式并且永遠不會到達列印命令?
uj5u.com熱心網友回復:
本質上,這就是您的代碼的作業方式:請注意,縮進用于顯示它正在運行的“函式”。
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 所說的那樣。
uj5u.com熱心網友回復:
遞回函式是有效嵌套的,因此您將列印行print(num)呼叫為 7,然后函式再次以 6 開始,因此再次呼叫您的列印行為print(num)6。
一旦到達 0,就會在每個函式遞回完成時呼叫底部陳述句。
所以你對于 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
雖然我沒有在每行之間列印出單獨的遞增數字
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/383338.html
下一篇:迭代牛頓的遞回方法(Java)
