Python Forum
Function returns unaccurate value - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Function returns unaccurate value (/thread-14291.html)



Function returns unaccurate value - raulfloresgp - Nov-23-2018

This is an example of an issue that I have:

why if a function calls another function the return of the called function is not accurate:

I have inserted some print instructions to evidence the outputs. thank you for your help.
def multiplicacion(a,b):
    producto = a*b
    print producto
    if a>b:
        return producto
    if b>a:
        a += 1
        multiplicacion(a,b)
    print str(producto) + "END"
    return producto


def maths(a, b):
    pluss = multiplicacion(a,b)
    print str(pluss) + " end "

maths(5, 6)



RE: Function returns unaccurate value - ichabod801 - Nov-23-2018

Please use python and output tags when posting code and results. I put them in for you this time. Here are instructions for doing it yourself next time.

This is the output I got:

Output:
30 36 36END 30END 30 end
That seems accurate to me. You call maths, maths calls multiplication(5, 6). That goes to line 2, which makes producto 30, which line 3 prints. Then it calls multiplication (6, 6) on line 8. That goes back to line 2, making product 36, which is printed. Then, both if clauses are skipped, because 6 == 6. So line 9 prints 36END. Then producto is returned to the previous call of multiplication, which ignores it. So we go to line 9 again, which prints 30END. 30 (the value of producto in the first call) is then returned to maths, which prints '30 end'.

What were you expecting?


RE: Function returns unaccurate value - raulfloresgp - Nov-23-2018

Thank you for your response!

What I expect is the value of "36END" to be returned to math function, but I don't know why it's ignored as you tell, I have tried to put "else" instead of the second "if" in multiplicacion function.


RE: Function returns unaccurate value - ichabod801 - Nov-23-2018

Like I said, the 36 gets ignored, because you don't do anything with the value of multiplication(a, b) on line 8. There's two ways you could get the 36 at the end. Either assign multiplication(a, b) to producto, or return it.


RE: Function returns unaccurate value - raulfloresgp - Nov-23-2018

I just get it, thank you so much!!! I was lost in this like for days, I'm starting to lear python and this site and your help just saved me!

def multiplicacion(a,b):
    producto = a*b
    print producto
    if a>b:
        return producto
    if b>a:
        a += 1
        producto = multiplicacion(a,b)
    print str(producto) + "END"
    return producto


def maths(a, b):
    pluss = multiplicacion(a,b)
    print str(pluss) + " end "

maths(5, 6)