Passing parameters to functions

Discussion in 'Python' started by Thomas Philips, May 24, 2004.

  1. The following program passes parameters (inluding another function)
    into a function.

    def f(myfunc,m=3,*numbers):
    sumSquares=myfunc(*numbers[:m])
    print sumSquares

    def sumofsquares(*args):
    total = 0
    for i in args:
    total += i**2
    return total

    f(sumofsquares,m=2,1,2,3,4,5)

    I have two questions:

    1. When I run it, Python gives me the following error message:
    Syntax error. There's an error in your program: *** non-keyword arg
    after keyword arg

    I get exactly the same error message if I edit the code and put the
    keyword argument first, i.e. def f(m=3,myfunc,*arguments):

    It, however, works correcly if I rip "m=2" out of the function call
    and write f(sumofsquares,2,1,2,3,4,5). The error message is not very
    helpful - surely everything after the m=2 should be swept into
    *arguments. What's the error in my logic?

    2. f passes *arguments[:m] into sumofsquares. It appears to be passing
    a pointer. But Python doesn't have pointers (except perhaps in its
    implentation), so what is it really doing? Is it just sheer dumb luck
    that makes my code work? I could logically define sumfsquares via

    def sumofsquares(args):
    ..
    and call it with
    sumSquares=myfunc(arguments[:m])

    but I am curious as to why my original form worked at all.

    Thomas Philips
    Thomas Philips, May 24, 2004
    #1
    1. Advertising

  2. (Thomas Philips) writes:

    > 1. When I run it, Python gives me the following error message:
    > Syntax error. There's an error in your program: *** non-keyword arg
    > after keyword arg


    As the error message says: Keyword args (your m=2) need to go at the
    end. At least according to my copy of "Programming Python" chapter 8.
    Tor Iver Wilhelmsen, May 24, 2004
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Robert Brewer

    RE: Passing parameters to functions

    Robert Brewer, May 24, 2004, in forum: Python
    Replies:
    3
    Views:
    400
    =?ISO-8859-1?Q?Holger_T=FCrk?=
    May 26, 2004
  2. teju
    Replies:
    9
    Views:
    643
    Chris Thomasson
    Jan 9, 2008
  3. Ramon F Herrera
    Replies:
    8
    Views:
    473
    Pascal J. Bourguignon
    Sep 13, 2009
  4. JBB123
    Replies:
    1
    Views:
    482
    JBB123
    Dec 8, 2011
  5. Frank Meyer

    Passing two functions as parameters

    Frank Meyer, Aug 16, 2007, in forum: Ruby
    Replies:
    8
    Views:
    121
    Frank Meyer
    Aug 17, 2007
Loading...

Share This Page