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

In my previous question, Andrew Jaffe writes:

In addition to all of the other hints and tips, I think you're missing something crucial: your functions actually need to return something. When you create autoparts() or splittext(), the idea is that this will be a function that you can call, and it can (and should) give something back. Once you figure out the output that you want your function to have, you need to put it in a return statement.

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

    print(parts_dict)

>>> autoparts()
{'part A': 1, 'part B': 2, ...}

This function creates a dictionary, but it does not return something. However, since I added the print, the output of the function is shown when I run the function. What is the difference between returning something and printing it?

This question is related to python return

The answer is


I think you're confused because you're running from the REPL, which automatically prints out the value returned when you call a function. In that case, you do get identical output whether you have a function that creates a value, prints it, and throws it away, or you have a function that creates a value and returns it, letting the REPL print it.

However, these are very much not the same thing, as you will realize when you call autoparts with another function that wants to do something with the value that autoparts creates.


The below examples might help understand:

def add_nums1(x,y):
    print(x+y)

def add_nums2(x,y):
    return x+y 

#----Function output is usable for further processing
add_nums2(10,20)/2
15.0

#----Function output can't be used further (gives TypeError)
add_nums1(10,20)/2

30
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-124-e11302d7195e> in <module>
----> 1 add_nums1(10,20)/2

TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'

Unfortunately, there is a character limit so this will be in many parts. First thing to note is that return and print are statements, not functions, but that is just semantics.

I’ll start with a basic explanation. print just shows the human user a string representing what is going on inside the computer. The computer cannot make use of that printing. return is how a function gives back a value. This value is often unseen by the human user, but it can be used by the computer in further functions.

On a more expansive note, print will not in any way affect a function. It is simply there for the human user’s benefit. It is very useful for understanding how a program works and can be used in debugging to check various values in a program without interrupting the program.

return is the main way that a function returns a value. All functions will return a value, and if there is no return statement (or yield but don’t worry about that yet), it will return None. The value that is returned by a function can then be further used as an argument passed to another function, stored as a variable, or just printed for the benefit of the human user. Consider these two programs:

def function_that_prints():
    print "I printed"

def function_that_returns():
    return "I returned"

f1 = function_that_prints()
f2 = function_that_returns()

print "Now let us see what the values of f1 and f2 are"

print f1 --->None

print f2---->"I returned"

When function_that_prints ran, it automatically printed to the console "I printed". However, the value stored in f1 is None because that function had no return statement.

When function_that_returns ran, it did not print anything to the console. However, it did return a value, and that value was stored in f2. When we printed f2 at the end of the code, we saw "I returned"


def add(x, y):
    return x+y

That way it can then become a variable.

sum = add(3, 5)

print(sum)

But if the 'add' function print the output 'sum' would then be None as action would have already taken place after it being assigned.


A function is, at a basic level, a block of code that can executed, not when written, but when called. So let's say I have the following piece of code, which is a simple multiplication function:

def multiply(x,y):
    return x * y

So if I called the function with multiply(2,3), it would return the value 6. If I modified the function so it looks like this:

def multiply(x,y):
    print(x*y)
    return x*y

...then the output is as you would expect, the number 6 printed. However, the difference between these two statements is that print merely shows something on the console, but return "gives something back" to whatever called it, which is often a variable. The variable is then assigned the value of the return statement in the function that it called. Here is an example in the python shell:

>>> def multiply(x,y):
        return x*y

>>> multiply(2,3) #no variable assignment
6
>>> answer = multiply(2,3) #answer = whatever the function returns
>>> answer
6

So now the function has returned the result of calling the function to the place where it was called from, which is a variable called 'answer' in this case.

This does much more than simply printing the result, because you can then access it again. Here is an example of the function using return statements:

>>> x = int(input("Enter a number: "))
Enter a number: 5
>>> y = int(input("Enter another number: "))
Enter another number: 6
>>> answer = multiply(x,y)
>>> print("Your answer is {}".format(answer)
Your answer is 30

So it basically stores the result of calling a function in a variable.


The print statement will output an object to the user. A return statement will allow assigning the dictionary to a variable once the function is finished.

>>> def foo():
...     print "Hello, world!"
... 
>>> a = foo()
Hello, world!
>>> a
>>> def foo():
...     return "Hello, world!"
... 
>>> a = foo()
>>> a
'Hello, world!'

Or in the context of returning a dictionary:

>>> def foo():
...     print {'a' : 1, 'b' : 2}
... 
>>> a = foo()
{'a': 1, 'b': 2}
>>> a
>>> def foo():
...     return {'a' : 1, 'b' : 2}
... 
>>> a = foo()
>>> a
{'a': 1, 'b': 2}

(The statements where nothing is printed out after a line is executed means the last statement returned None)


Major difference:

Calling print will immediately make your program write out text for you to see. Use print when you want to show a value to a human.

return is a keyword. When a return statement is reached, Python will stop the execution of the current function, sending a value out to where the function was called. Use return when you want to send a value from one point in your code to another.

Using return changes the flow of the program. Using print does not.


you just add a return statement...

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

printing out only prints out to the standard output (screen) of the application. You can also return multiple things by separating them with commas:

return parts_dict, list_of_parts

to use it:

test_dict = {}
test_dict = autoparts()