Last answered:

07 Dec 2021

Posted on:

18 Nov 2021

3

Hello, why return instead of print

Hi there,

Why is it we type return instead of print on this video, while the previous one, after if statement, we type print.

Thank you

1 answers ( 0 marked as helpful)
Instructor
Posted on:

07 Dec 2021

3

Hi Yenni!

Thanks for reaching out!

We use return when we want to return some result. But nothing is shown on console. To have the result in the console, we use print.
Let me show you an example. If you have:

def multiplication_by_2(x):
   print(x*2)

We call the function with an argument and it works! Fantastic!
But if you want to use

def multiplication_by_2(x):
   return x*2

What do we have here? The same function but instead of having print on the second row, we have return. So, if we invoke our function with an argument of 5 (i.e. by executing ), nothing will be shown in the console. So, we can use print in the following way:

def multiplication_by_2(x):
   return x*2
result=multiplication_by_2(5)
print(result)

When this code is executed it shows 10.
To sum it up, when using print in a function, we are just displaying the function's result. And so, the function will work. When using return, we will only store the result of the function when invoked. We can later display that result by using the print() function outside the function we had created (in this example - multiplication_by_2(5).

Hope this helps.
Best,
Martin

Submit an answer