作者feather2 (飛羽)
看板Python
標題[問題] 關於遞迴的回傳值
時間Wed Jul 1 15:42:08 2020
小弟不才 最近才剛入門python 3
其中寫了兩個簡單的函式
第一個是使用遞迴方式 其中原本預期能回傳出做到第幾次(c)將終止
雖然有print 四次的c 但是回傳值消失
小弟寫了第二個使用while迴圈的方式 就能成功印出四次的c 並回傳出最後一次的c
實在想不出來是為什麼遞迴的方法return 不出來
請教各位高高手
def test(c, a, n):
c=c+1
b=(a+n)/2
if b<=(n/2+3):
print(c)
return c
else:
print(c)
test(c, b, n)
test(0, 10, 5) #print:1, 2, 3, 4
##############################
def test1(c, a, n):
t=0
while True:
t+=1
b=(a+n)/2
if b<=(n/2+3):
print(t)
return t
else:
print(t)
a=b
test1(0, 10, 5) #print: 1, 2, 3, 4;output: 4
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.109.236.130 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1593589330.A.AEC.html
推 ddavid: 遞迴return只會回上一層啊,你遞迴else那邊test(c, b, n) 07/01 16:12
→ ddavid: 又沒人接return值,最深層的4怎麼可能傳回最上層 07/01 16:13
→ ddavid: 直覺上應該改成return test(c, b, n),我沒細看不知道有沒 07/01 16:13
→ ddavid: 有其他bug 07/01 16:13
→ feather2: 懂了 感謝 07/01 16:55