Home > Software design >  Refer to first returned value of function in python
Refer to first returned value of function in python

Time:09-21

I want to refer to the first returned element of a function.

I have a function that returnes two values: x2 and y2.

In the next function, I want to refer to the first value. How is that done? An example of my attempt here:

def helper1(x,y):
    return x*2,y*2

def helper2(x,y):
    helper1(x,y)
    a = 2/helper1[0] #here I try to refer to the first element returned of helper1, but doesn't work :( 
    return a

any ideas?

CodePudding user response:

def helper1(x,y):
    return x*2, y*2

def helper2(x,y):
   a = 2/helper1(x, y)[0]   # how to access to the 1st value of helper1
   return a  # no idea of what is a

print(helper2(3, 4))
#0.3333333333333333

CodePudding user response:

You just stuck the function there instead of the result of the function.

Here I'm calling the function and getting the [0] before I divide. By the way, are you trying to assign the input a in a "pass by reference" style? Because I don't think that's going to work.

def helper1(x,y):
    return x*2,y*2

def helper2(a,x,y):
    a = 2/(helper1(x,y)[0]) #helper1(x,y)[0], not helper1[0]

CodePudding user response:

Try something like:

>>> def helper2(x, y):
...     tmp = helper1(x,y)    
...     a = 2/tmp[0]

Note that you need to store the result of calling helper1(x,y). You can then acces the first element of that result biy indexing, e.g tmp[0]

Alternatively you could have done

...     a = 2/helper1(x,y)[0]

avoiding the use of a temporary variable

CodePudding user response:

alpha, beta = helper1(x, y)
a = 2 / alpha
  • Related