作者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://webptt.com/cn.aspx?n=bbs/Python/M.1593589330.A.AEC.html
1F:推 ddavid: 递回return只会回上一层啊,你递回else那边test(c, b, n) 07/01 16:12
2F:→ ddavid: 又没人接return值,最深层的4怎麽可能传回最上层 07/01 16:13
3F:→ ddavid: 直觉上应该改成return test(c, b, n),我没细看不知道有没 07/01 16:13
4F:→ ddavid: 有其他bug 07/01 16:13
5F:→ feather2: 懂了 感谢 07/01 16:55