[Tutor] 'return'

Magnus Lyckå magnus@thinkware.se
Sat May 31 06:29:08 2003


At 16:45 2003-05-30 -0500, Jennifer Cianciolo wrote:
>what is the difference between 'return' and 'print'?

With the print statement the expression after "print" is
sent to the screen (or a file). Print can occur anywhere.

The return statement ends a function, and returns the
expression after "return" to the caller of the function.

If you call a function in an interactive session and don't
assign the return value to anything, the interpreter will
display that value on th screen.

Example:

 >>> def add(a,b):
...     return a + b
...
 >>> add(1,2)
3

In this case, the practical result was the same as if we had
used "print" in the function, but only in an interactive
session. In a program you would need "print add(1,2)"

 >>> x = add(1,2)
 >>> print x
3

Here, we assign the return value to a new variable "x".
It's not printed until we explicitly print x. Another
examples follow below.

 >>> a = b = 1
 >>> while a < 20:
...    old_b = b
...     b = add(a, b)
...    a = old_b
...     print a,
...
1 2 3 5 8 13 21

As you see, return and print have entirely different
intentions.

The issue of print vs return pops up as beginners often
write functions that prints a value and then end (and
return None, which is the default value to return if no
return statement is present).

Such a function is a "dead end". It can only be used to
show a value. If the function returns the value instead
of printing it, the caller can decide whether to print
it, use it in further calculations or both. It gives much
more options to the caller, i.e. the function is more
widely useful.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The shortest path from thought to working program