Students seeing a programming language for the first time and using Python's REPL for the first time have asked me what is the difference between a return statement and a print() call. They got a point.
--8<---------------cut here---------------start------------->8--- def f(x): return x + 1 >>> f(1) 2 >>> print("hello") hello --8<---------------cut here---------------end--------------->8--- There's no visual difference. (*) My answer The way I know how to answer the difference there is to explain how a typical computer system works, which is a more or less long answer. A return statement is usually just another CPU instruction, while /print/ is a procedure that must eventually run a CPU instruction that interrupts the CPU, passes control to the operating system which, in turn, talks to the i/o devices in question (the video, for example) to get the job finally done. (We may expect a print() call, therefore, to be usually much slower than a return statement.) I also explain that if, say, math.sin(x) is going to print a message to the screen... >>> sin(pi/2) calculating your sine... hang on... 1.0 ... I might as well not use it because this will get mixed with my own print() statements and I'll be surprised about who added that calculating-your-sine message. So adding print() statements to procedures is, in practice, rare. (To them it's the most typical operation because they never do any serious programming and they learn their first steps out on the Internet. In my course, print() is only allowed after at 10th homework, after 10 weeks.) I also explain that if f(x) prints its answer to the screen instead of returning it, it will be harder to capture the answer in a variable. For example, >>> def f(x): ... print(x + 1) ... >>> f(1) 2 >>> y = f(1) 2 >>> y >>> >>> y == None True I take this opportunity to remark that Python seems to always returns something, even if it's the ``special'' value None. (*) The REPL I also explain that the REPL is just another program. Its purpose happens to be to [r]ead, [e]val, [p]rint and [l]oop, which is why we get to see return values printed to the screen. (*) My insatisfaction I wish I had simpler answers. Explaining about operating systems, the CPU, system calls... I wish there was an easier way to clarify such things. You guys might have ideas. I'm thinking about showing them the code for the simplest toy-REPL so that we can perhaps demystify the REPL. I think they see the REPL as part of the programming language, so I think it might help to figure out that nothing happens unless code is written to make it happen. If something gets displayed on the screen, there is definitely some i/o going on and print() is the one initiating that i/o, while return is just another ``arithmetic'' operation such as addition. Thank you so much. -- https://mail.python.org/mailman/listinfo/python-list