Newbie question...
David Porter
jcm at bigskytel.com
Wed Sep 27 10:10:45 EDT 2000
* jhorn94 at my-deja.com <jhorn94 at my-deja.com>:
> I'm going thru the Learning Python book and am stumpped. The exercise
I'm (slowly) reading it too!
> calls for a function that accepts and arbitrary number of keyword
> arguments, then returns the sum of the values. I can step thru the
> arguments with a for statement, but I can't figure out how to accumlate
> a sum of the values. Any help is appreciated.
>
> def adder(**args):
>
> for x in args.keys():
> y=y+x
> return y
>
> print adder(good=1, bad=2, ugly=3)
> print adder(good="a", bad="b", ugly="c")
returns
> UnboundLocalError: y
because there is no y to add x to.
The following should do what you want:
def adder(y, **args):
for x in args.values():
y=y+x
return y
print adder(good=1, bad=2, ugly=3, y=0)
print adder(good="a", bad="b", ugly="c", y='')
I changed args.keys() to args.values() so that the values of the keywords
are added and not the keywords themselves. I also added y as a keyword, though
there might be a better way to do this. I did this because adding numbers
requires y to be different than when concatenating characters.
David
More information about the Python-list
mailing list