0
I made a simple function in Python to give me the sum of the numbers n until 0:
def retorna(n, zero, soma):
if n <= zero:
soma += n
return soma
retorna(n+1, zero, soma)
ret = retorna(1, 5, 0)
print(ret)
The result of the function, as it is 1. But if I put print (soma)
in place of return soma
(and call the function without print
), she gives me:
1, 3, 6, 10, 15.
Why does this happen? I wanted to be able to display only the last result, 15, in case.
Can you help me and give me one more example to understand?
The goal is to practice recursion ? Because this would be much easier and make a lot more sense iteratively.
– Isac
Almost, the goal is to learn recursion.
– Iago Paschoal
@Iagopaschoal Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already done so. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).
– Maniero