[Tutor] when to use "return" or "print"

Alan Gauld alan.gauld at yahoo.co.uk
Tue Sep 29 04:49:47 EDT 2020


On 29/09/2020 08:44, ScribusP wrote:

> But at the moment I am stuck with the question, when it is best to use
> "return" and when it is best to use "print". Could you give me some
> examples, please?

print is very limited in its use. You only use it when you want to
display something on the user's console. It doesn't work in GUIs on
web pages or when using background programs to process files or
network data etc.

return, on the other hand, is how you pass back values(and control)
from inside a function to the calling program.

Here is a simple example of when *not* to use print:

def add(x,y))
    print(x+y)    #returns None by default

total = add(5,4)  # prints 9 and returns None

print (total)     # prints None!

double = total * 2   # ERROR! Can't multiply None

Now consider if we used return instead:

def add(x,y):
   return x+y

total = add(5,4)
print(total)        # now prints 9

double = total * 2  # can now use the result of the function
print(double)       # prints 18


So usually we try to avoid print inside a function(except
for debugging during development) and instead return values.
The higher level code can do any printing needed.
This means we can use our functions in places where
print would not work (eg. as part of a GUI program) or
would not be seen (a server background process).

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list