What’s the difference between using Return and print in this recursive function that calculates the sum of numbers?

Asked

Viewed 295 times

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.

  • Almost, the goal is to learn recursion.

  • @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).

2 answers

4

First, this code works better iteratively and not recursively. Let’s learn recursion with problems that need to be recursive and learn better.

A basic error is that it is not returning the recursion result, it is just calling the function and throwing out its result. And you’re still doing it conditionally since you’re inside the if, cannot, it must perform every time except the last.

The code could have more significant variable name to know what it is. The sum of n looks like a meaningless line there, should have the sum in the recursive function.

Except last time the return should always be the function’s own result, every recursion is like this.

def retorna(valor, limite, soma):
    if valor > limite:
        return soma
    return retorna(valor + 1, limite, soma + valor)
print(retorna(1, 5, 0))

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thanks. One more thing, if you can... I don’t understand the stopping criteria. Why doesn’t it stay in infinite looping? since it is forever return the "return(value + 1, limit, sum + value" ???

  • @Iagopaschoal you didn’t see that has one if? Ali sets the tone. Read the part Exceto na última vez?

  • I saw the if. It does not leave the if and then falls into the "Return returns(value........)"???

  • @Iagopaschoal you understand what a if? And what is a return?

  • So far, I thought so. if is part of the conditional structure. If a comparison after the if is true, then what is nestled inside the if runs. In the case of a contrary, what is nestled inside the if is not executed. Return returns some value to the function. (but I don’t think I’m quite clear on the concept of Return in my head yet). The question continues... and if you can recommend something about Return, thank you.

  • Yeah, the return terminates the function and nothing else runs on it.

  • Wow, now I get it. Return not only returns a value, it works as a break. Just one more thing. What is the difference between calling the function with ""Return returns(value + 1, limit, sum + value)"" or without Return, just like this ""returns(value + 1, limit, sum + value)""?

  • What you need to learn in a structured way, there are a lot of little details that make all the difference. Learning on demand doesn’t usually work, it creates the illusion you’re learning. Programming is understanding everything that’s going on, not having a view over it. The first is returning the value of the called function, the second is not.

  • Thanks. And where I learn the structured way?

  • Top Books and Courses.

Show 5 more comments

2

If the function should return the sum of a set of integers, we can mathematically define the problem. Let us consider that the interval is defined by a and b: [a, b], being b greater than or equal to a. So we have:

inserir a descrição da imagem aqui

This expression can be expanded as:

inserir a descrição da imagem aqui

And it’s trivial to realize that it can be rewritten as:

inserir a descrição da imagem aqui

Which is nothing more than the recursive form of the sum function. But this cannot be infinite, otherwise your program will run eternally. We need a situation where recursive writing can be simplified, generating what we call a stop condition.

For this example, we can analyze the situation when the interval [a, b] arrives in the particular case where a is equal to b, getting:

inserir a descrição da imagem aqui

That is, when a = b, we know the sum will only be b.

So we can define our function somar, who receives the values a and b:

def somar(a, b):
    return a + somar(a+1, b) if a < b else b

So, as expected, as we do somar(1, 5) we will have the result 15.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.