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
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