[Tutor] Return T/F vs print T/F

Steven D'Aprano steve at pearwood.info
Sat Feb 4 17:53:05 CET 2012


Sivaram Neelakantan wrote:
> While trying out code, I have trouble following the difference between 
> return True vs print True and the same with False.  If I use return
> for the True/False statements, nothing gets printed.  Why? 

Probably because you aren't printing anything. Python can't read your mind and 
know what you want printed and what you don't want printed, you have to tell 
it what to print.

It is not clear how you are "trying out code". Are you running code as a 
script? Using IDLE or iPython? Using the standard interactive interpreter? The 
environment will make a difference in the behaviour.

In the interactive interpreter, as a convenience, the result of each line is 
automatically printed for you:


 >>> 1+3
4
 >>> len("hello world")
11


but this is only in the interactive environment. In a script, nothing is 
printed unless you call print.

Functions should have a return result -- the value they calculate. You can 
then store the value in a variable for later use:

 >>> length = len("hello world")  # store the value
 >>> print "The length is", length  # and use it later
The length is 11


The print command does not return a value, it just prints the argument. If you 
use print in the function, you cannot capture the result and use it in 
additional calculations.

When writing your own functions, you should always aim for this same 
behaviour: use return inside the function, print outside.



> And if I add a print before the function call I get an output like 
> 
>>>> True
> None

I can't see any possible way your code will give output including ">>>". Would 
you care to explain more carefully what you mean?




-- 
Steven




More information about the Tutor mailing list