It is not the same thing. In your example it seems to be, but it is because it is not a good example.
If you dig a little deeper, you’ll see that when used print
, although the correct value is displayed, the value of x
that receives the return function will be null, None
.
>>> def media(a, b):
... print((a+b)/2)
>>> x = media(1, 3)
2
>>> print(x)
None
That is, when using the print
the result is sent to buffer output and then discarded. The value x
, that would receive the result, receives a null value, because the function has no return.
Different if you use the return
, because the value will be returned by the function and assigned in x
:
>>> def media(a, b):
... return (a+b)/2
>>> x = media(1, 3)
>>> print(x)
2
Note that even calling the function, the output is not displayed until the print(x)
, because the function sends the return to x
and no longer for the buffer outgoing.
Imagine that you need to add 5 on average between 1 and 3. Using print
you won’t be able to do x+5
, for x
is null, since the function had no return - and it is not possible to add 5 to null. Already using the return
, the result 2 will be stored in x
and thus it will be possible to add 5.
Ideally, a function should not use print
, unless this is explicitly its goal: to display the data. A function that calculates the media should not have the responsibility of flaunt the average. This breaks the principle of sole responsibility and leaves your code barely reusable.
When you use the return
, you will have direct access and power to manipulate the function return, which generates a much more versatile and malleable code for you.
Imagine the following problem:
- Add the average between 1 and 3 with the average between 7 and 9.
Using the print
, the first average result, 2, will be displayed on the screen as well as the second average result, 8. You will need someone to manually sum up 2 and 8 to get the result 10.
When you use the return
, you can access the results within the program yet:
>>> x = media(1, 3)
>>> y = media(7, 9)
>>> x+y
10
You don’t need to know what the partial results are to get the total; if by chance you need to change media(7, 9)
for media(7, 11)
, the result x+y
will automatically become 11.
It is not the same thing. Try to check the value of
x
for you to see.– Woss
@Andersoncarloswoss that ended up giving me one more question. What I got was the following: >> print(x) None >>> print(y) 5.0 ?
– Pablo Leonardo