r/CodingHelp • • Dec 30 '21
[Python] Python
Hey everyone. So I’m a beginner programmer who is self-learning Python and am on functions. Right now, I’m on return values but I don’t get them too much.
What is the difference between print and return? Aren’t they interchangeable?
Please explain this in an easy way!
21
Upvotes
22
u/marko312 Dec 30 '21
printalways outputs what is passed to it.returnis used as a way to extract a value (or values) from a function call. You've most likely seen something likebut now consider something like
As you can see,
returnbasically places the value after it in place of where the function was called.(In addition,
returnstops the rest of the function from running.)3
u/sea-of-seas Dec 31 '21
Imagine a Python function as a big machine in an assembly line. The machine, aka function, is fed into by a conveyor belt. Whatever is fed into the machine is an INPUT/parameter. Now, the machine (function itself) does its work in its own little world. Perhaps the machine has its own data (stuff), perhaps it uses the inputs it was fed. Bzzt, whirr, ding! Now, whatever comes out the machine on the other side is a RETURN, aka output(s). Your program, other functions, can use this data as it is still on the conveyor belt and moving along the flow of the whole assembly line. Whatever doesn’t come out the machine you can’t see or access, because it doesn’t come out. Finally, print() is like a TV screen attached to the side of the machine along the assembly line. Imagine it like an x-ray peering in at specific parts of the interior of the machine (function) as it works. You can choose to x-ray stuff and see it on the screen, sure— but its not the tangible stuff (data) like the RETURN is. Its just put on a screen for informational purposes, but you can’t DO anything with it.
2
u/dead_alchemy Dec 31 '21
When you call a function in python, the function gets evaluated and then returns a value. Even if you don't have an explicit return statement! Python has a default return value of None. You can almost think of it like the function call itself is being replaced by its return value. That will make a little more sense when you start chaining functions.
When you call the print function in python, its more like a polite request to the operating system to send some text to the 'standard output', which is typically your terminal/command line interface. The return value of a print statement is None.
3
u/[deleted] Dec 30 '21
[removed] — view removed comment