Newbie question...

shindich at my-deja.com shindich at my-deja.com
Wed Sep 27 22:01:36 EDT 2000


In article <mailman.970063727.7536.python-list at python.org>,
  =?iso-8859-1?Q?Max_M=F8ller_Rasmussen?= <maxm at normik.dk> wrote:
> From: jhorn94 at my-deja.com [mailto:jhorn94 at my-deja.com]
>
> >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.
> >
> >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")
>
> First, you are trying to make a function that can add both numbers and
> strings. This is probably not what is meant in the exercise.
>
> But the following function will do it.
>
> -------------------------------------------
> def adder(**args):
>     result = 0               # set initial value to 0
>     for x in args.values():  # ask for the values
>         result = result + x  # ad x to the result
>     return result
>
> print adder(good=1, bad=2, ugly=3)
>
> print adder(good="a", bad="b", ugly="c")# This won't work as i tries
to add
>                                         # strings, and the "result"
value
>                                         # inside the function is
intialised
>                                         # as a number.
> -------------------------------------------
>
> To add strings you can change the method to:
>
> -------------------------------------------
> def adder(**args):
>     result = ''              # this is the change
>     for x in args.values():
>         result = result + x
>     return result
>
> print adder(good="a", bad="b", ugly="c") # Then this will work.
>
> Regards Max M
>
>
Huh? Since when do you need to write separate functions for adding
numbers and strings in Python? The buty of the language is that you can
write template-like function easily.
The following function will do the job:
def foo (**args):
	retVal = None
	for arg in args.values ():
		if retVal:
			retVal = retVal + arg
		else:
			retVal = arg
	return retVal

>>> foo (good=1, bad=2, ugly=3)
6
>>> foo (good='1', bad='2', ugly='3')
'123'


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list