Diffrence bettween print() and return

what is diffrence bettween print() and return

I presume you’re new to Python.

print() prints the value to the output.
return returns the value of the function - basically the value of f() (e.g. the value of variable x in x = f())

yeah im new but can i have some more details about return function

Functions are like short segues from the main flow of the program. A diversion, as it were. return is how we get back to the main flow once the function code has executed. It knows where the first instruction following the diversion resides and will resume normal flow from that point. That’s its first purpose–know where to return.

What’s more, it is able to communicate to the caller the locations of any values the function may have created so they can be rescoped to that of the caller.

As we will have learned, functions have their own local scope. Values created in that scope are not accessible to the outside (global scope). return hands back the references so they can be assigned to variables or used in statements outside of the function.

So, return knows where to resume in normal flow, and gives the locations (references) of the return values to the caller.


Study this example for a moment:

def foo(x):
    x *= 2
    print (id(x))
    return x

>>> y = foo(21)
2558314415632    #  location of the value referenced by x
>>> id(y)
2558314415632    #  location of the value referenced by y
>>>

The id() function is built in to Python’s Standard Library and allows us to find the location in memory of a given value.

Note that the location of y is the same as x, even while the former is outside of the function. This is thanks to return.


This is made all the more meaningful whence we learn that Python is very greedy with memory and simply refuses to allow two identical values to exist in memory (unless they are themselves reference objects such as lists, tuples, sets, or dictionaries). In other words, primitive values are only ever stored once, regardless how many places they are referred from.


a = [1,2,3,4,5,6]
b = [1,2,3,4,5,6]

>>> id(a)
2558351705408
>>> id(b)
2558351705984
>>>

Note that even though the two lists are identical, they make up two separate references. It will be no surprise, though, to find that the values they contain do have the same reference.

>>> id(a[5])
2558314414480
>>> id(b[5])
2558314414480
>>> 
4 Likes

this is exceptionally clear. thank you for saving me a bunch of time!

1 Like