开发者

Python: Adding new line after return in recursive function

I am new to python and faced the following problem.. I am trying to do a recursive sum function but the sum does not get returned on a new line

For example, sum(2,2) should return

4开发者_如何学编程
2

sum(2,3) will return

6
4
2

But I get 4 2 and 6 4 2 all on the same line. This is my code:

def sum(a,b):
    if a>0 and b>0:
        return str(a*b) + " " + str(sum(a,b-1))
    else:
        return ""

I have tried use changing " " to "\n" but it doesn't work


def sum(a,b):
    if a>0 and b>0:
        return str(a*b) + "\n" + str(sum(a,b-1))
    else:
        return ""

works fine here.


You wrote that changing " " to "\n" doesn't work, but did you try printing the result?

print sum(2, 2)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜