Difference between returns and printing in python?

67,810

Solution 1

The Point

return is not a function. It is a control flow construct (like if else constructs). It is what lets you "take data with you between function calls".

Break down

  • print: gives the value to the user as an output string. print(3) would give a string '3' to the screen for the user to view. The program would lose the value.

  • return: gives the value to the program. Callers of the function then have the actual data and data type (bool, int, etc...) return 3 would have the value 3 put in place of where the function was called.

Example Time

def ret():
    return 3

def pri():
    print(3)

4 + ret() # ret() is replaced with the number 3 when the function ret returns
# >>> 7
4 + pri() # pri() prints 3 and implicitly returns None which can't be added
# >>> 3
# >>> TypeError cannot add int and NoneType

Solution 2

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.

Solution 3

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

Solution 4

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.

Share:
67,810
Admin
Author by

Admin

Updated on October 12, 2020

Comments

  • Admin
    Admin over 3 years

    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!

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