[英]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 我是python的新手,遇到了以下问题。我试图做一个递归求和函数,但是求和不会在新行上返回
For example, sum(2,2) should return 例如,sum(2,2)应该返回
4
2
sum(2,3) will return sum(2,3)将返回
6
4
2
But I get 4 2 and 6 4 2 all on the same line. 但是我在同一行上得到4 2和6 4 2。 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 我尝试使用将“”更改为“ \\ n”,但是它不起作用
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. 在这里工作正常。
您写道将“”更改为“ \\ n”无效,但是您尝试打印结果吗?
print sum(2, 2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.