Passing parameters to functions

T

Thomas Philips

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
 
T

Tor Iver Wilhelmsen

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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top