0

So, I have a function:

def function(x,y,z):
    result = (x+y)/z
    print(result)

I want to assign a result with a specific set of arguments to an object:

data = function(20,10,5)
data

This function with these values should give me 6 as an answer, which it does. However, when I enter "data", to which I assigned this result, nothing happens. I want to store this result to another object so I can call it lates.

I looked up a bit for an answer before posting and also tryed:

class test:
    def __init__ (self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
    def result(self,x,y,z):
        res = (x+y)/z
        print(res)

p2 = test(20,10,5)
data = p2.result(20,10,5)        
data

I feel like this second try of mine probably don't make any sense. Sorry if it's a dumb question, but I'm a begginer and couldn't find the answer elsewhere.

Thanks in advance!

Alvarez
  • 29
  • 1
  • Use `return res`, instead of `print(res)` to return value back to caller. So it gets assigned to `data`. – Austin Nov 13 '18 at 17:45
  • `data` itself does nothing. did you mean to `print(data)`? and instead of printing the result you should `return result`. – hiro protagonist Nov 13 '18 at 17:46
  • You are just printing the result, but not returning it, so, by default, the return value of the function is `None`, which is what gets assigned to `data`. Replace `print(res)` with `return res`; calling the function will not show anything, but you can then do `print(data)` (or simply write `data` in the command line) to see the result. See [What is the purpose of the return statement?](https://stackoverflow.com/q/7129285) – jdehesa Nov 13 '18 at 17:46
  • I don't think, that this is a good SO question as it can be googled very easily – user8408080 Nov 13 '18 at 17:48
  • Thanks for the answers. I tryed googling but answers are often way more complex than what i needed. Plus, i didnt know I should return instead of printing. So the wording on the googling may have been wrong also. Thanks for all who answered. – Alvarez Nov 13 '18 at 17:53

2 Answers2

1

Your function should return the value instead of printing it:

def function(x,y,z):
    result = (x+y)/z
    return result
João Eduardo
  • 452
  • 5
  • 10
0

You need to return instead of printing it:

def function(x, y, z):
    result = (x + y) / z
    print(result)  # only prints and does not return a thing
    return result
vishes_shell
  • 22,409
  • 6
  • 71
  • 81