Shared publicly  - 

I'll definitely switch to Python 3.2 (you're my role model, and I can't believe you're even reading my words! :-), and I'll spread it around faster than you can say (insert really long sentence.)

And I know that you told me not to send you something regarding help with the language, but I can't help it. If you do not have time to answer it, don't. I have tried emailing, and it was very helpful, but I was still stranded on the (awesome) desert of Python, and since only one person was responding to my emails, I didn't want to bug him too much. I really have tried to find resources to help me, but I just can't find them. Please!!!

Anyways, the question is, why would you use the return statement? Couldn't you just use print? I need a simple definition, and how and why you would use it.

Thanks, and really sorry, (Guido guides me!)

--Eager Correspondent

Dear Eager Correspondent,

Your question baffles me. If you have to ask this, I don't think I can answer in a way you would understand.

I'll ask my followers for the most concise explanation.
Hugo Fernandez's profile photoGuillaume Gauvrit's profile photoTrae Santiago's profile photobacon bannana's profile photo
No need to be rude, and no, the manual doesn't explain when to use return vs. print.
OH come on you know it was funny... Google+ may be the best place on the internet, but it's still the internet!
so is it mean that it is the time we all use py3x to replace 2x?
Wisecracking is no way to help the uninitiated, and 20 years after it was first uttered I can't say I find RTFM funny any more...
it way easier to reuse an returned object than a string representation of it, that is why return is way more handy
Print outputs to stdout immediately upon execution, if one wanted to take the results of a function, and perform another transform on those, or pass them to yet another function, one would assign the returned content to a variable which would allow those actions. If the only way you are using functions is print function() then there is no benefit, and one could use print inside the function just as easily. (Although I would consider it to be poor form, and in large application it can become a nightmare to debug.)
An alternate scenario would be thus:

myvariable = function()
myvariabletransformed = transform(myvariable)
print myvariabletransformed
Bingo, I like that one (the one by +Andrew Rodgers). Thanks!
Return gives the data back to you to keep using in your program, print gives the data to the user to look at.
if your answer refers to me, you are welcome
+Justin Lilly I like your description in the first paragraph, however, I think you are forgetting the powerful role that stdin/out play in the *nix world, and how print can be used to interact through those features. Are you better off with an api? absolutely, but for quick hacks (esp with really large packages) access to the stdout can be a lifesaver.
the data got by return usually mean that i want to use the data later but print maybe i just want to see how program runs
I liked +Andrew Rodgers explaination, that's pretty much the gist of it.
Sometimes you want the output of a function to be used on more than one thing, so return allows you to use that as a variable :)
As your ambitions and skills grow, you will (you will; everyone does!) discover that your programs seem to become too complex to manage using the techniques which you have mastered so far.

You'll learn a lot of ways to overcome this problem, but one very basic tool for managing complexity in programming is "separation of concerns". Another way to say that -- sticking with the topic of returning versus printing -- that the code which manipulates data should not be the code which generates or prints that data.

The code for manipulating data should be put into a function which returns the result of the manipulation (the transformed data). The transformed data can then be printed. It can also be sent over a network. It can also be sent to a second function, which will produce a further transformation.

And the function itself can be called from anywhere you need that transformation done, so that you don't have the same block of code appearing in your program every time you need to do a certain thing.

Functions which transform and return data are the building block of almost all the techniques you'll learn as you grow as a programmer: decoupling, code reuse, refactoring, modules and libraries, objects, and on, and on.
+Robert Roland hmm I consider myself VERY beginner and I understood +Justin Lilly 's response a little more because it was a little less programmer-speak than the other one.. but the other one certainly sounded a lot more.. um techno-legit let's say
Hmm... let's assume that the person asking this is thinking in terms of shell scripting (that's only one reason one might confuse the two). In that case, the answer is slightly different. When you do something like this in a shell (say, Bourne Shell or Bash):


you run the program named "program". It executes, does whatever it needs to do, and when it exits its output (which is printed out using "print" if it's a simple Python program) is captured by your script and stored in FOO. Starting up that program and capturing its output is a lot of work, but if it does far more work, that extra overhead might not be significant.

In Python (as in modern shells, it turns out) you can place your work into a function, and when it runs, there's no new program for the computer to run, just a little bit of code, like this:

def myfunction():
return false

Now foo is set to false, and there's only slightly more work being done than if you just wrote:


Of course, this is a trivial example, but functions are powerful. just one trivial example of why:

def area(width, height):
return width * height
def volume(width, height, depth):
return area(width, height) * depth
print "The area of the unit cube is:", area(1,1,1)

Edit: Imagine there's formatting above :-/
My explanation would be:
return Your_Teddy_Bear
is much pleasing than
print 'Your Teddy Bear' # the words
If you get an email asking for help, you can

a) formulate an answer and return it by sending an email response back to the person who asked you. That person can then do anything she wants with the response.

b) you can print your answer on a piece of paper. If the person who asked you wanted the answer to be printed on a piece of paper, that's fine. However, that person will not be able to do anything with your answer.
This person is probably confused by interactive mode.

I have found the difference between interactive mode and ordinary source files, which largely is largely about the implicit print associated with expressions, is one of the most confusing things to beginners. Typically the instructor sort of glides by this and the persistent student eventually gets used to it first and then figures it out. This seems likely to be an instance of that confusion.

I think there ought to be a didactic mode whereby the REPL loop behaves more like the ordinary flow of the language. The convenience of printing the value of expressions is a didactic mess.

This is a very common confusion among the Python students I've taught over the years. I think it boils down to the fact that most introductions to programming don't really explain what expression evaluation is all about, and instead just hope that students catch on after seeing enough examples.
I think +Michael Tobis is right. Explaining what a REPL is and what's going on is really important. I wonder if a Lisp is the right thing to start with, where you must return something all the time and side effects are special cases, not the norm.
Here's another approach: I wonder if this guy ever imports modules?

How useful could any module be to your program if it could only print results to screen and never return anything useful to your program?
I like +Justin Lilly's answer, since I think it uses language at a level that a novice unfamiliar with programming (and *NIX) is more likely to be understand. I also think that +Michael Tobis is spot on - for beginners working in interactive mode there often seems to be no apparent difference between return and print for built-in types.
Look at python as a system, with the outside world to interact with.
Calculations and other stuff to do, is done within this system. The 'outside world' is a terminal, a screen, a printer, ... so with 'print' you send something to the outside. With 'return' you stay within the python system.
For the record, my 14 yo knows the answer to this question. I won't bore everyone with another rehash of the simple answer, but I can be proud. :-)
Actually I can understand why someone might be confused by this. In some sense "print" does "return" a value --- to the user.

Eager Correspondent: The "return" statement in Python (and similar features in almost all computer programming languages) allow a function to return a value to another part of the program (which called upon them).

The whole point of defining functions (for example with Python's "def" keyword) is to create a way for various other parts of a program to refer to some sequence of operations by name, to supply their invocations of those functions (the calls to them) with data (arguments) and for those bits of code to have some mechanism for passing results back.

By defining functions one can build very complex systems by composing them of functions which call on other functions which, in turn call on others. This is only possible because these functions, at each level, can pass values down to those they need to call, receive the values that are returned by those functions, and can further manipulating them (combining them with other results, passing those into other functions and so on).

If all you could do within your function is "print" your results then someone (or something outside of your program) would have to capture those results and somehow feed that back in to some other program. You wouldn't be able to get very far under such conditions.

The degree of confusion you're seeing from others who read this question is, in large part, because these concepts: call, arguments, and return, are the most fundamental in all of programming. It's as if you asked why anyone would use a cup instead of a fork for drinking coffee.
Very simple answer:
You can't use something you print, because you show the value to the user and the result is lost. Instead with "return" the value goes back to the program. Rememeber that when you write functions it's because you are gonna using ("calling") them many times, and combine them.
I have found to be an immensely helpful place when I have python questions. A politely framed question will be answered very quickly.
return is used when you are writing functions.
Print just displays a value on a screen. Return gives back a value so another part of a program can use it.
You know when you use a string method, like string.upper(), or string.find(), and they give you back data (the string in all upper case for example) the person who wrote those methods likely used Return, to give you that new data back. print wouldn't have worked because you couldn't use that data.
+Stefano Cavallari has nailed the issue. I've seen this many times in the introductory programming classes that I teach. Some students have difficulty in recognising the difference between returning data to the program and printing it from within the function. Confusion tends to occur because many of the programs that they encounter before learning about functions will simply print output to the console.
I wonder if the Python tutorial is to blame. The only use of return in section 4.6 is to replace a print(), and in the example the value is immediately printed after it's returned. You can't blame someone for wondering why they bothered to not just print it in the function.
+Geoffrey Spear I don't think it is just down to the tutorial. I've seen lots of examples where the first function definitions introduced to students simply print values; indeed, I'm guilty of doing this myself!
Haha +***** got troll'd. On the odd chance that our noob isn't pressing his luck, I'd tell him:

Imagine you've climbed a tree and found apples. Printing would be like shouting: "Here are apples". Where as a return statement is like taking them down.
Likewise, the former is useful if you have someone listening, the latter is useful if you want to do something with the apples afterwards. 
I've found in mentoring beginners that often ideas like this are best expressed with a physical demonstration. Student hands you a sticky note, you scribble on it and stick it to the whiteboard (print). They hand you another sticky note, you scribble on it and hand it back (return).
I don't think there's a way to explain this that I would have understood. This sort of thing becomes obvious once you've needed to use the functionality.
I'll give it a try:

Print is to send output to the user. Return is to send a value to another function that may be calling this one.
print should be removed from the language for Python 4. Real programs want or sys.stdout.write or whatevergui.displaysomethingsomewheresomehow today.
Many computations can be split into small steps and we can mix and match these small steps to build new complex computations.
return is needed to store intermediate results of small steps in a computation. print is used to show final result of the computation to the user.
Print is invaluable for beginners. It's intuitive and gives a quick answer (and is useful for basic debugging). sys.stdout.write is far more intimidating for the person with no programming experience.
At the risk of stating the obvious, 'return' is more useful than 'print' -- in any language that supports these constructs, not just Python -- because programs aren't really just programs, they're APIs or programming frameworks. Other programmers will, inevitability add functionality and maintain any useful program. The best advice I can give is to read The Art of Unix Programming by Eric Raymond:

This pretty much deepens the discussion that I'm greatly summarizing in this post.
You can say Rather than RETURN you an answer, how about I PRINT it out? Surely, one of us will see it and it will do one of us some good but if I RETURN it, you can then PRINT it out yourself and RETURN the favor to anybody else with the same question. OK?. Then maybe you can say something cool.
Isn't that what I just said?
The basic concepts that must be undestood by anyone starting to learn programming are: 1) computation as input->processing/side-effects->output, with the middle part itself being composed of a sequence of input->processing/side-effects->output, and 2) IO -- usually what the side-effect part is about. He is confusing the use of "print" (output to a device) with "return" (computing output to be used on another computing sequence ou to be used for device output).
The 1st part can be compared with functions in mathematics, to some point. The 2nd with usually takes a quick hardware and OS course.
As a teacher I can tell you this isn't exactly an uncommon question. I'm not sure how I would advise explaining the difference over an email - it's hard for long time programmers to realize the amount of detail necessary to learn programming the first time. For instance, if you assume he even knows what a string, or variable for that matter, is you might be assuming too much. 
+Cia Con Dive into Python is great if you already have some programming notions, but the person making this kind of question lacks even basic undertanding of computing.
Guido, your answer is good, but here is the underlying didactic problem.

>>> s = "a=5;a"
>>> exec(s)
>>> a=5
>>> a

The particular instance in question probably looks something like this:

>>> def f(): a=5; return a
>>> f()
>>> def g(): a=5; print a
>>> g()

It would be much clearer to the beginner if the transcript looked like this:

>>> a=5
>>> a
}}} print(a)
>>> f()
}}} print(f())
>>> g()
}}} print(g())
I'd be worried this "}}}" transcript notation would solve more problems than it causes. It doesn't look particularly clean or clear to me.
I'm not actually suggesting "}}}", just pointing out that the implicit print causes confusion at an early phase where it is difficult to explain. In practice this could be in a different color, or could just magically appear on the input line when the input is an expression rather than an assignment.

Perhaps the best thing is for beginners not to have the P in REPL at all.

My point is that the question is understandable in the context of a beginner learning about functions via the REPL interface, and that I have ducked other versions of this question myself. Imagine what this does to high school teachers who don't have a good grasp on the matter themselves.
Now I'm going to propose a PEP for changing return into a function..
I agree that it is likely the Python interpreter that illuminates the print/return confusion. But I am not sure it causes it, and I wouldn't want to have to give up the interpreter to address this one issue.

We don't see the same sort of confusion among our Java/C++ students, and I doubt that's because they all understand what return means (they certainly show other kinds of confusion about return, e .g. not realizing it immediately exits a function).

I think it is symptom of not really understanding expression evaluation and control flow. And maybe those two things need to be taught more explicitly to beginners.
I am not suggesting that the interpreter be drastically changed for the benefit of the rank beginner. I am suggesting that it have a less confusing, albeit less convenient, beginner mode, so that the issue does not come up until the beginner has more familiarity with the concepts.

It is quite difficult to explain what the interpreter does in its Print phase to someone who is not familiar with the distinction between expressions and statements. The Python syntax allows one to avoid getting to this level of abstraction, but the interpreter stomps on it. And I would say it is the most promising students who get confused and discouraged.
See iPython (which should be strongly recommended to all beginners anyway):
In [1]: def a():
...: return "123"

In [2]: a()
Out[2]: '123'

In [3]: print "123"
Print is used for humans, while return is used for the computer.

Print will show the value on the screen, while return will send the value back to who called the function. If you called your function from the interactive shell, it will automatically print the returned value. You may however also capture the value and do further work.

For example, if you make a function for calculating the price of a bag of apples:

def applePrice(appleCount):
pricePerApple = 3
return appleCount * pricePerApple

then you can easily test this function on its own in the shell:

>>> applePrice(5)

but the reason you made this function is to use it as part of a bigger task:

>>> milkPrice = 4
>>> breadPrice = 2
>>> total = milkPrice + breadPrice + applePrice(2)
>>> print "The total is", total, "euros"
The total is 12 euros

This shows how print is used for humans, while return is used for the computer. You can add 4+2+(whatever number returned), but you can not (easily) capture what a function printed, as by then the value is just letters on the screen, potentially mixed with text for the user.

Programming usually involves building and combining such functions and using them from within other functions, each performing a separate task, but as a whole achieving the desired result.
It's the wrong question. The interesting question is: "why do you use print when you can just use return?" I am serious!
Imagine you have a function called sum() that adds two numbers together. Now do a=sum(1,2); b=sum(4,5); c=sum(a,b). You return gets the value computed in sum() back to the variables a, b, and c.
I think another important learning aspect is the realisation that all those magic standard functions *) you have been using are not any different from the functions you are writing.

This enables you to move away from the view of system and module functions floating up in the attic disconnected from the world of your own functions - and realise that when you run a program it's calling a function that calls another function which calls another function, etc., but each of them simply just do a particular job and are combined in different ways.

*) Ignoring native functions which unfortunately still are quite a few in Python - in Lisp this can be much more obvious - even Java has most of its APIs written in Java.
Wow, I'm impressed that some of these respondents were able to put themselves into the questioner's shoes enough to (probably) understand where he was coming from and how the question arose. I was so unable to understand the question that it was like it was in a foreign language. Are any of you teachers? Maybe you should be.
Maybe a beginners guide to programming would be a nice start
+Clarence Gardner Yeah, I had to read a few comments to figure out they meant executing a function in the interpreter and not a file. I was totally confused.
I would also point the user to the comp.lang.python group. A lot of very helpful pythonistas hang out there
I have thought about it and in fact, in a shell it's done like that.

You can write this dummy hello word

import sys
def say_hello():
return "hello {0}".format(sys.argv[1])
print say_hello().upper()

in bash like that

function say_hello {
echo "Hello $name"
say_hello | tr '[:lower:]' '[:upper:]'

the echo is in the function, and the pipe is the way you "catch" the return of the function to modify it.

Please, do not write a PEP to remove the return statement ;)
hahha. I'm still using python 2.4 on my server. We're not switching yet. Not sure why.
Add a comment...