What Is the Purpose of the Return Statement? How Is It Different from Printing

What is the formal difference between print and return?

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.

The difference between ‘print’ and ‘return’ in Python

print() sends output to your console via standard output. return sends output to whatever called your function. If you want to use recursion, you need to use a return statement, not print().

Here's an example:

def sum2(l):
if l == []:
return 0
else:
return l[0] + sum2(l[1:])

sum2([1, 2, 3])
# 6

This is recursive because the return statement contains a call to the function itself. Generally, a good thing to learn about in a computer science class but a bad thing to do in production code.

How is returning the output of a function different from printing it?

print simply prints out the structure to your output device (normally the console). Nothing more. To return it from your function, you would do:

def autoparts():
parts_dict = {}
list_of_parts = open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v = line.split()
parts_dict[k] = v
return parts_dict

Why return? Well if you don't, that dictionary dies (gets garbage collected) and is no longer accessible as soon as this function call ends. If you return the value, you can do other stuff with it. Such as:

my_auto_parts = autoparts() 
print(my_auto_parts['engine'])

See what happened? autoparts() was called and it returned the parts_dict and we stored it into the my_auto_parts variable. Now we can use this variable to access the dictionary object and it continues to live even though the function call is over. We then printed out the object in the dictionary with the key 'engine'.

For a good tutorial, check out dive into python. It's free and very easy to follow.

python - difference between print and return

Return stops execution of a whole function and gives the value back to the callee (hence the name return). Because you call it in a for loop, it executes on the first iteration, meaning it runs once then stops execution. Take this as an example:

def test():
for x in range(1, 5):
print(x)
return x

test()

This will give the following output:

1

This is because the for loop starts at 1, prints 1, but then stops all execution at the return statement and returns 1, the current x.


Return is nowhere near the same as print. Print prints to output, return returns a given value to the callee. Here's an example:

def add(a, b):
return a + b

This function returns a value of a+b back to the callee:

c = add(3, 5)

In this case, c, when assigning, called add. The result is then returned to c, the callee, and is stored.

What is the use of a return statement?

Normally, when you call a function, you want to get some result. For example, when I write s = sorted([3,2,1]), that call to sorted returns [1,2,3]. If it didn't, there wouldn't be any reason for me to ever call it.

A return statement is the way a function provides that result. There's no other way to do that, so it's not a matter of style; if your function has a useful result, you need a return statement.


In some cases, you're only calling a function for its side-effects, and there is no useful result. That's the case with print.

In Python, a function always has to have a value, even if there's nothing useful, but None is a general-purpose "no useful value" value, and leaving off a return statement means you automatically return None.

So, if your function has nothing useful to return, leave off a return statement. You could explicitly return None, but don't do that—use that when you want the reader to know you're specifically returning None as a useful value (e.g., if your function returns None on Tuesday, 3 on Friday, and 'Hello' every other day, it should use return None on Tuesdays, not nothing). When you're writing a "procedure", a function that's called only for side-effects and has no value, just don't return.


Now, let's look at your two examples:

def helloNot():
a = print("Heya!")

This prints out Heya!, and assigns the return value of print to a local variable, which you never use, then falls off the end of the function and implicitly returns None.

def hello():
a = print("Heya!")
return a

This prints out Heya!, and assigns the return value of print to a local variable, and then returns that local variable.

As it happens, print always returns None, so either way, you happen to be returning None. hello is probably a little clearer: it tells the reader that we're returning the (possibly useless) return value of print.

But a better way to write this function is:

def hi():
print("Heya!")

After all, we know that print never has anything useful to return. Even if you didn't know that, you know that you didn't have a use for whatever it might return. So, why store it, and why return it?



Related Topics



Leave a reply



Submit