[問題] 關於遞迴的回傳值

看板Python作者 (飛羽)時間3年前 (2020/07/01 15:42), 編輯推噓1(104)
留言5則, 2人參與, 3年前最新討論串1/1
小弟不才 最近才剛入門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

07/01 16:12, 3年前 , 1F
遞迴return只會回上一層啊,你遞迴else那邊test(c, b, n)
07/01 16:12, 1F

07/01 16:13, 3年前 , 2F
又沒人接return值,最深層的4怎麼可能傳回最上層
07/01 16:13, 2F

07/01 16:13, 3年前 , 3F
直覺上應該改成return test(c, b, n),我沒細看不知道有沒
07/01 16:13, 3F

07/01 16:13, 3年前 , 4F
有其他bug
07/01 16:13, 4F

07/01 16:55, 3年前 , 5F
懂了 感謝
07/01 16:55, 5F
文章代碼(AID): #1U_3vIhi (Python)