-5

I've been scrolling through Google for a while now and I'm yet to find an answer for this. Let's say I have:

def equation(a, b):
    price = (a + b) * 2
    return price


def main():
    equation(5, 10)
    print(price)

and I want to print price through main(), how do I do this? Whenever i run it, it says something like price is not defined

Skryptix
  • 3
  • 3
  • did you try returning something in your first function? look there. I believe you can figure this out! :) – MattR Mar 27 '18 at 14:18
  • 5
    Possible duplicate of [What is the purpose of the return statement?](https://stackoverflow.com/questions/7129285/what-is-the-purpose-of-the-return-statement) –  Mar 27 '18 at 14:19
  • Do you want to (A) transfer the _value_ of `price` from `equation` to `main`, or (B) simply make the `price` _variable_ accessible to both `equation` and `main`? – GoBusto Mar 27 '18 at 14:19
  • 2
    Calling a function doesn't automatically store its return value in a magically created variable. If you want to get the return value in the `price` variable, you have to assign it there: `price = equation(5, 10)`. – Aran-Fey Mar 27 '18 at 14:20
  • make `price` accessible to both – Skryptix Mar 27 '18 at 14:20
  • In that case, you'll need to make `price` a [global](https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python) variable, rather than a local one. However, please note that [this is considered bad practice](http://wiki.c2.com/?GlobalVariablesAreBad) - instead, you should try to `return` it to `main` as a local variable, as described in the [suggested duplicate](https://stackoverflow.com/questions/7129285/what-is-the-purpose-of-the-return-statement) linked to above. – GoBusto Mar 27 '18 at 14:26

1 Answers1

0

That's because although you call the function you don't save its return value anywhere. Try instead

def main():
    price = equation(5, 10)
    print(price)

Note also that the variable in the calling function doesn't need to relate to naes inside the called function (which are generally only available inside the function). So you could equally well write

def main():
    some_other_name = equation(5, 10)
    print(some_other_name)
holdenweb
  • 33,305
  • 7
  • 57
  • 77