Newbie question...

Hans Nowak ivnowa at hvision.nl
Wed Sep 27 16:00:28 CEST 2000


jhorn94 at my-deja.com wrote:

> I'm going thru the Learning Python book and am stumpped.  The exercise
> 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")
> 
> Traceback (most recent call last):
>   File "C:\Python16\Pythonwin\pywin\framework\scriptutils.py", line
> 301, in RunScript
>     exec codeObject in __main__.__dict__
>   File "C:\Python16\examples\lpython\sol\CH4EX4.PY", line 8, in ?
>     print adder(good=1, bad=2, ugly=3)
>   File "C:\Python16\examples\lpython\sol\CH4EX4.PY", line 4, in adder
>     y=y+x
> UnboundLocalError: y

y must have an initial value... try inserting  y = 0  before the for.
Aside from that, you probably want to use args.values() rather than
args.keys().

This won't work for your second line (good="a", etc) though, because it
uses strings for values, and y is initialized as an integer.

If you want a more generic function, you could try:

def adder3(**args):
    return reduce(lambda x, y, a=args: x+y, args.values())

>>> print adder3(good=1, bad=2, ugly=3)
6
>>> print adder3(good="a", bad="b", ugly="c")
"abc"


-- Hans Nowak

-----BEGIN PYTHON CODE BLOCK-----
Version: 1.0
Py+++ v1.5.2,1.6 ev+,i,p n+++ s++++ tt+++,w+ a1996 w---#
ow95,w98,wnt,d6,d7,l
lc++,cc++,pa+++,sc+,b++# m- b3 fs--- r9
------END PYTHON CODE BLOCK------



More information about the Python-list mailing list