To view the results of your python code, the standard function most of us are taught to call in our previous basic python code article is the print() function which shows the results of your code. However, there’s a different function known as return which seemingly does the same thing but yet isn’t exactly quite the same. So what is the difference between print and return in Python? It’s actually a very fine line.
To explain this, we turn to our Python shell, to define a function retu and prin
print (x +3)
and when you call the 2 functions
they both return a value of 8. Which is why many, including myself, can get confuse about the difference between the two functions. However, while the output is the same, what happens behind the scenes is actually different.
In a layman’s explanation, the print function is used when you want the code is concluded and you want it to be readable by a human. Python hence “prints” the code out in a readable format. If the code is unconcluded and you still wish for python to continue reading your code and/or use the code in later codes, you should use return instead.
To make the difference more apparent, we can assign a new variable to the previous two mentioned function. x_r for return and x_p for print
you will realise that x_r had no output but x_p returned 8. Why is this so? It’s because throughout the whole process of python trying to understand x_r, there was no code that told it to specifically show and print what x_r is. This is even more apparent when you add a mathamatical equation to the function
gives you a value of 16
prin(5) * 2
gives you an 8 and an error.
Confusing? Well not quite if you just try and understand it from a layman’s human and computer language point of view. From the moment the print function is used, python converts the code into a human language. Hence after converting it to human language, it can no longer use it to do the * 2 multiplication as it no longer understands the code past converting prin(5) into 8.
However, if you use the return function, the code stays in computer language and hence is still able to do the mathematical calculation on python’s terms.
In conclusion, to be able to master Artificial Intelligence, we learn python over other coding language like HTML because we want to be able to understand computer language and we code in a way so that Python understands us and we can eventually tell Python to do what we want it to do in the language it understands.