[Tutor] functions in Python
Alan Gauld
alan.gauld at freenet.co.uk
Mon Apr 17 22:05:02 CEST 2006
Wow! I checked the list at lunchtime and there were only a few things
here, then I check again now and lots of stuff from my tutor! Fortunately
most of it has been answered already - thanks folks - but I feel honour
bound to contribute something...
> What is the difference between,
>
>>>> def f(x):
> ... return x
>>>> def f(x):
> ... print x
> ...
>>>> f(4)
> 4
> Both give same results. So, why return statement is needed?
As has been stated the print displays on the output
The return sends the value of the function back to the caller.
If the caller is the interactive prompt(as here) the prompt
prints the value so the effect is the same.
If you need to save the result for later use then you must
store it in a variable. You cannot do that if the function
just prints the result - the value gets lost when the function
ends.
Try this:
>>> def f(x): return x
...
>>> def g(x): print x
...
>>> fVal = f(4)
>>> gVal = g(4)
4
Now notice that the two functoons behave differently
f() doesn't display a value but g does because of the
print statement. So far g seems to win. But...
>>> print fVal
4
>>> print gVal
None
>>>
Now f() wins because we have stored its value in fVal
and can use it over and over again as we wish.
The reason gVal has stored None is because any function that
does not return an explicit value is treated as retiurning the
special value None. Since g() only printed the parameter 4
but did not return it gVal stored a None value.
If we return the value of f() we can display it any time we
want by using print:
>>> print f(4)
4
>>>
So we do not lose anything by using return instead of print
but we gain a lot by being able to store the returned value.
HTH,
Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list