0

This is an example code that is reading off of a pandas dataframe with a names lengths widths, and height, all of which contain floats under each name variable. I am trying to return each of the floats under their respective variable, but I can't seem to figure out how to return multiple variables. Any help would be appreciated.

def volume(length, width, height):
    for i in pdf[length]:
        return (i)
    for i in pdf[width]:
        return (i)
    for i in pdf[height]:
        return (i)

print (volume('length', 'width', 'height'))

bnicholl
  • 306
  • 2
  • 13
  • Is there a missing `def` at the beginning? And shouldn't the rest of the code be indented? – Barmar Mar 04 '17 at 00:07
  • You can't use `return` multiple times in a function. You should return a tuple with all the values. It's not clear why you have `for` loops, though. – Barmar Mar 04 '17 at 00:09
  • 1
    Possible duplicate of [How do you return multiple values in Python?](http://stackoverflow.com/questions/354883/how-do-you-return-multiple-values-in-python) – Beck Yang Mar 04 '17 at 00:24
  • yea my bad, i messed up when i copied it – bnicholl Mar 04 '17 at 01:32

1 Answers1

1

You can return a tuple or a dictionary, and assign it to variables:

With a tuple:

volume(length, width, height):
    ....
    return (pdf[length], pdf[width], pdf[height])

and then invoke the function unpacking the tuple, like this:

l, w, h = *volume(x, y, z)

or a dictionary

return {'length': pdf[length], 'width': pdf[width], 'height': pdf[height]}

In which case you can assign the result into a single dictionary variable and reference each value by key (for example: result['width'])

And lastly, you could also use an object with 3 separate member variables. If you think it's worth defining a class for your program.

JavoSN
  • 464
  • 3
  • 12
  • 1
    Shouldn't it be `return pdf[length], ...`? – Barmar Mar 04 '17 at 00:09
  • True. I wasn't clear if he's returning just the 3 dimensions, or a list of 3 dimensions. The for loops confused me. I'll expand the code, and wait for OP to clarify – JavoSN Mar 04 '17 at 00:16
  • Confused me, too. – Barmar Mar 04 '17 at 00:23
  • My logic was the lists which are put in the object that I am calling have around 7 floats per string name, which is why I used a for loop. – bnicholl Mar 04 '17 at 02:11
  • @bnicholl ok. But how many values or whats the data structure that you expect to return? – JavoSN Mar 04 '17 at 02:18
  • @JavoSN I was trying to return each string argument('length', 'width', 'height') and put them each into their own separate list. – bnicholl Mar 04 '17 at 03:59