Newbie question...

Max Møller Rasmussen maxm at normik.dk
Wed Sep 27 10:03:25 EDT 2000


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




More information about the Python-list mailing list