It's not the same thing. In your example it seems to be, but it's because it's not a good example.
If you look a little deeper, you'll see that when you use print
, even though the correct value is displayed, the value of x
that gets the return of the function will be null, None
.
>>> def media(a, b):
... print((a+b)/2)
>>> x = media(1, 3)
2
>>> print(x)
None
That is, using print
output is sent to the output buffer and then discarded. The value x
, which would receive the result, is given a null value, since the function has no return.
Different if you use 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
Notice that even when calling the function, the output is not displayed until the print(x)
is executed, because the function sends the return to x
and no longer to the output buffer .
Imagine that you need to add 5 on average between 1 and 3. Using print
you will not be able to x+5
, because x
is null, since the function has no return - and it is not possible to add 5 in null. Already using return
, result 2 will be stored in x
and thus it will be possible to add 5.
Ideally, a function should not use print
, unless it is explicitly its purpose: to display the data. A function that calculates the average should not have the display to average. This breaks the principle of single responsibility and leaves your code somewhat reusable.
When you use 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 print
, the result the first average, 2, will be displayed on the screen, as well as the result of the second mean, 8. Will someone need to manually make the sum of 2 and 8 to get the result 10. p>
When you use return
, you can access the results within the program yet, you can do:
>>> x = media(1, 3)
>>> y = media(7, 9)
>>> x+y
10
You do not need to know the partial results to get the total; if you need to change media(7, 9)
to media(7, 11)
, the result x+y
will automatically become 11.