What is the formal difference between “print” and “return”? [duplicate]

Dramatically different things. Imagine if I have this python program:

#!/usr/bin/env python

def printAndReturnNothing():
    x = "hello"
    print(x)

def printAndReturn():
    x = "hello"
    print(x)
    return x

def main():
    ret = printAndReturn()
    other = printAndReturnNothing()

    print("ret is: %s" % ret)
    print("other is: %s" % other)

if __name__ == "__main__":
    main()

What do you expect to be the output?

hello
hello
ret is : hello
other is: None

Why?

Why? Because print takes its arguments/expressions and dumps them to standard output, so in the functions I made up, print will output the value of x, which is hello.

  • printAndReturn will return x to the caller of the method, so:

    ret = printAndReturn()

ret will have the same value as x, i.e. "hello"

  • printAndReturnNothing doesn’t return anything, so:

    other = printAndReturnNothing()

other actually becomes None because that is the default return from a python function. Python functions always return something, but if no return is declared, the function will return None.


Resources

Going through the python tutorial will introduce you to these concepts: http://docs.python.org/tutorial

Here’s something about functions form python’s tutorial: http://docs.python.org/tutorial/controlflow.html#defining-functions

This example, as usual, demonstrates some new Python features:

The return statement returns with a value from a function. return without an expression argument returns None. Falling off the end of a function also returns None.

Leave a Comment