argument matching question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Learning Python

    #1

    argument matching question

    I know this is dummy, just never saw an example of this.


    I want to use the special argument matching.

    A code like this:

    def adder(**varargs ):
    sum=varargs[varargs.keys()[0]]
    for next in varargs.keys()[1:]:
    sum=sum+varargs[next]
    return sum

    print adder( "first","second ",'third')


    ------------------------
    It pop up error like this:

    Traceback (most recent call last):
    File "learn.py", line 7, in ?
    print adder( "first","second ",'third')
    TypeError: adder() takes exactly 0 arguments (3 given)


    How to pass arguments to a functions that use dictionary collection?


    Thanks

  • Leif K-Brooks

    #2
    Re: argument matching question

    Learning Python wrote:[color=blue]
    > A code like this:
    >
    > def adder(**varargs ):
    > sum=varargs[varargs.keys()[0]]
    > for next in varargs.keys()[1:]:
    > sum=sum+varargs[next]
    > return sum
    >
    > print adder( "first","second ",'third')
    >
    > How to pass arguments to a functions that use dictionary collection?[/color]

    Like adder(foo="bar" , bar="baz"), but I think you really want a function
    like this:

    def adder(*args):
    sum = args[0]
    for value in args[1:]:
    sum += value
    return sum

    Comment

    • Learning Python

      #3
      Re: argument matching question

      thanks, got it.
      I want to test the **name option for argument matching.

      Comment

      • Scott David Daniels

        #4
        Re: argument matching question

        Leif K-Brooks wrote:[color=blue]
        > Learning Python wrote:
        >[color=green]
        >>A code like this:
        >>
        >>def adder(**varargs ):
        >> sum=varargs[varargs.keys()[0]]
        >> for next in varargs.keys()[1:]:
        >> sum=sum+varargs[next]
        >> return sum[/color][/color]

        For that function, call:
        print adder(first=1, second=2, third=3)

        A better function definition for python 2.4 would be:
        def adder(**varargs ):
        return sum(varargs.val ues())
        And a better function definition without using sum would be:
        def adder(**varargs ):
        values = varargs.values( )
        if values:
        total = values[0]
        for element in values[1:]:
        total += element
        return total
        else:
        return 0

        --Scott David Daniels
        Scott.Daniels@A cm.Org

        Comment

        Working...