views:

76

answers:

4

In python I don't seem to be understanding the return function. Why use it when I could just print it?

def maximum(x, y):
    if x > y:
        print(x)
    elif x == y:
        print('The numbers are equal')
    else:
        print(y)

maximum(2, 3)

This code gives me 3. But using return it does the same exact thing.

def maximum(x, y):
    if x > y:
        return x
    elif x == y:
        return 'The numbers are equal'
    else:
        return y

print(maximum(2, 3))

So what's the difference between the two? Sorry for the mega noob question!

+4  A: 

What would you do if you need to save printed value? Have a look at good explanation in docs and cf.:

>>> def ret():
    return 42

>>> def pri():
    print(42)


>>> answer = pri()
42
>>> print(answer)         # pri implicitly return None since it doesn't have return statement
None
>>> answer = ret()
>>> answer
42

It also is no different from return statement in any other language.

SilentGhost
+2  A: 

For more complex calculations, you need to return intermediate values. For instance:

print minimum(3, maximum(4, 6))

You can't have maximum printing its result in that case.

RichieHindle
`print minimum(3, maximum(4, 4))` does not work in OP's version :-(
eumiro
@eumiro: Isn't that exactly the point of RichieHindle's answer?
Tim Pietzcker
@Tim: Richie's example works with the second OP's version. Mine not.
eumiro
+1  A: 

Remember that the interactive command line isn't the only place methods will be called from. Methods can also be called by other methods, and in that case print isn't a usable way to pass data between them

Gareth
A: 

Honestly, it depends on what you need the function to do. If the function specification state that it will print out max term, then what you have is fine. What generally happens for a method like this is that the method should return the actual value which is larger. In the case they are equal, it doesn't matter which value is returned.

Shynthriir