0

I have a function and it's getting a bit long, and so I am wanting to break it up into multiple functions. My problem is I am trying to get a number of values out of one function and into another and am not sure how to do it.

For example,say I was using these values (my program is much bigger)

def mean():
    vitaminA = 5
    calcium = 15
    vitaminD = 22

how would I get each of these values into another function? I have tried:

def mean():
    vitaminA = 5
    calcium = 15
    vitaminD = 22
    return (vitaminA, calcium, vitaminD)

def stDev():
    mean()
    print vitaminA
    print calcium
    print vitaminD

What do I actually need to do? I thought if you return values from another function within a function you could access those values?

1
  • 2
    Your function is returning values, not variables. The caller can do whatever it wants with them. This could mean putting them into its own variables (with the same names or otherwise), or putting them all into a single tuple variable, or passing them directly along to another function, or ignoring them entirely. You have to tell Python which one of those you want to do. Your code is telling it that you want to ignore them. Commented Jun 25, 2013 at 1:22

2 Answers 2

5

You just need to assign the result of calling mean to a variable (or in this case, set of variables):

vitaminA, calcium, vitaminD = mean()
print vitaminA
print calcium
print vitaminD

Python allows you to unpack any iterable into variables:

x, y, z = (1, 2, 3)
print "x: {x}, y: {y}, z: {z}".format(**locals())

The same principal applies to generators:

def generator_func():
    yield "Even"
    yield "generators"
    yield "participate"

w1, w2, w3 = generator_func()
print w1
print w2
print w3
# Even
# generators
# participate

And in Python 3 you get unpacking as well:

head, *tail = range(1, 11)
print head  # 1
print tail  # [2, 3, 4, 5, 6, 7, 8, 9, 10]
Sign up to request clarification or add additional context in comments.

Comments

3

You're on the right track. By calling the mean() function you'll obtain the values that were returned there (in particular, the variables). Now you have to assign them in stDev(), to get a hold of the values - like this:

 vitaminA, calcium, vitaminD = mean()

Now stDev() has access to the values that originated in mean().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.