Inspecting, Printing, and Returning Values

Suppose you have some data stored in a variable in a function, like this function that doubles the input value:

def double(x):
    value = x * 2

How do you get value out of the function to the code that called it? For example, we want y below to have the value 14:

y = double(7)

You may recall that Python prompts (e.g., IDLE) will display values when you enter only an expression without assignment (recall assignment is something like x = ...) or if you print it:

>>> x = 7     # nothing displayed after assignment
>>> x         # displays 7
7
>>> print(x)  # also displays 7
7

... so maybe you can do this?

def double(x):
    value = x * 2
    value

But let's see:

>>> y = double(7)
>>> y         # nothing is displayed
>>> y == 14   # not the expected value
False
>>> print(y)  # y is 'None'?
None

... so what about print?

def double(x):
    value = x * 2
    print(value)

... now let's try again:

>>> y = double(7)  # displays 14 on assignment?
14
>>> y              # nothing
>>> y == 14        # still not the expected value
False
>>> print(y)       # still 'None'
None

When an expression is entered at the prompt without an assignment, its representation is displayed to the user, but otherwise there is no effect on the program. Let's call this value inspection. The same goes for printing, although printing always happens, and value inspection only displays a value when it is entered directly at the prompt. This is why the first version of double() displayed nothing when it was called but the second version did. These are both for reporting values in the program and not for changing any internal state.

If you want to have the value in the function be usable by the code that called the function, use a return statement:

def double(x):
    value = x * 2
    return value

Let's try that:

>>> y = double(7)  # nothing is displayed, ok
>>> y              # 14, yes!
14
>>> y == 14        # correct!
True
>>> print(y)       # ha!
14

Note that value inspection behaves differently when it is used at a Python prompt, in a Python module (e.g., when importing or executing a .py file), or in a Jupyter notebook. The following table explains when values are displayed to the user:

Mode Value Inspection Printing Return statement
Prompt always at a prompt always never*
Module never always never
Notebook only the last line in a cell always never*

And the following table explains when values are returned from a function:

Mode Value Inspection Printing Return statement
Prompt never never always
Module never never always
Notebook never never always