[Tutor] 'None' output after arbitrary agruments function
Jeff Shannon
jeff at ccvcorp.com
Thu Sep 9 19:56:45 CEST 2004
André Roberge wrote:
> adder doesn't return a value (hence, printing it returns none).
Or, more specifically, all functions return a value; if you don't
specify what that value should be, it defaults to None. You (the
O.P.) have already printed results within the function, and then you
*also* print whatever's returned from the function; since you haven't
specified what should be returned, what you get is None, and what
you're seeing is Python dutifully printing None just as you've told it
to do. :)
> Try the following (just calling adder, not printing it):
>
> def adder(*arg):
> x = arg[0]
> for y in arg[1:]:
> x = x + y
> print x
>
> adder('abc', 'def')
> adder(['aa', 'bb', 'cc'], ['dd', 'ee', 'ff'])
> adder(3.23, 1.77, 3.32)
Or, alternatively, since there's any number of things that you might
want to do with the results of adder(), instead of just printing them...
def adder(*arg):
x = arg[0]
for y in arg[1:]:
x = x + y
return x
print adder('abc', 'def')
print adder(['aa', 'bb', 'cc'], ['dd', 'ee', 'ff'])
temp = adder(3.23, 1.77, 3.32)
print temp, temp * 2
Note how this lets me do further manipulations on the sum that I get
from adder(), or simply store the result for later use elsewhere.
Usually it's considered better style to simply return calculated
results from a function, rather than printing them there -- the
exception to this being a function whose sole purpose is to print
something in a meaningful way. The idea here is that a function
should try to do only *one* thing; calculating a result is one thing,
printing it is a different thing.
Jeff Shannon
Technician/Programmer
Credit International
More information about the Tutor
mailing list