[问题] 关于递回的回传值

楼主: feather2 (飞羽)   2020-07-01 15:42:08
小弟不才 最近才刚入门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
作者: ddavid (谎言接线生)   2020-07-01 16:12:00
递回return只会回上一层啊,你递回else那边test(c, b, n)又没人接return值,最深层的4怎么可能传回最上层直觉上应该改成return test(c, b, n),我没细看不知道有没有其他bug
楼主: feather2 (飞羽)   2020-07-01 16:55:00
懂了 感谢

Links booklink

Contact Us: admin [ a t ] ucptt.com