473,486 Members | 2,162 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

function that accepts any amount of arguments?

if i want a function that can take any amount of arguments how do i
do?

lets say i want a function average that accepts any number of integers
and returns the average.
Jun 27 '08 #1
16 1218
globalrev wrote:
if i want a function that can take any amount of arguments how do i
do?
Put an asterisk before the argument name.

lets say i want a function average that accepts any number of integers
and returns the average.
def avg(*args):
return sum(args) / len(args)

There are some dangers (at least two glaring ones) with this code,
though, which I leave as an exercise for the reader.

:)

Paul
Jun 27 '08 #2
globalrev wrote:
if i want a function that can take any amount of arguments how do i
do?

lets say i want a function average that accepts any number of integers
and returns the average.
Use a parameter of the form *args - the asterisk tells the interpreter
to collect positional arguments into a tuple. Untested:

def mean(*x):
total = 0.0
for v in x:
total += v
return v/len(x)

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Jun 27 '08 #3

"globalrev" <sk*******@yahoo.sewrote in message
news:4d**********************************@w7g2000h sa.googlegroups.com...
| if i want a function that can take any amount of arguments how do i
| do?
|
| lets say i want a function average that accepts any number of integers
| and returns the average.

To add to the other comments, read the ref manual section of function defs.

Jun 27 '08 #4
Ken

"Steve Holden" <st***@holdenweb.comwrote in message
news:ma*************************************@pytho n.org...
globalrev wrote:
>if i want a function that can take any amount of arguments how do i
do?

lets say i want a function average that accepts any number of integers
and returns the average.

Use a parameter of the form *args - the asterisk tells the interpreter to
collect positional arguments into a tuple. Untested:

def mean(*x):
total = 0.0
for v in x:
total += v
return v/len(x)
think you want total/len(x) in return statement

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Jun 27 '08 #5
Ken wrote:
"Steve Holden" <st***@holdenweb.comwrote in message
[...]
>def mean(*x):
total = 0.0
for v in x:
total += v
return v/len(x)

think you want total/len(x) in return statement
Yes indeed, how glad I am I wrote "untested". I clearly wasn't pair
programming when I wrote this post ;-)

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Jun 27 '08 #6
Paul McNett a écrit :
>
def avg(*args):
return sum(args) / len(args)

There are some dangers (at least two glaring ones) with this code,
though, which I leave as an exercise for the reader.
try:
avg("toto", 42)
except TypeError, e:
print "this is the first one : %s" % e
try:
avg()
except ZeroDivisionError, e:
print "this is the second : %s" % e

As far as I'm concerned, I would not handle the first one in the avg
function - just document that avg expects numeric args.

Not quite sure what's the best thing to do in the second case - raise a
ValueError if args is empty, or silently return 0.0 - but I'd tend to
choose the first solution (Python's Zen, verses 9-11).
Jun 27 '08 #7
On Apr 24, 12:43*pm, Bruno Desthuilliers <bruno.
42.desthuilli...@websiteburo.invalidwrote:
[...]
Not quite sure what's the best thing to do in the second case - raise a
ValueError if args is empty, or silently return 0.0 - but I'd tend to
choose the first solution (Python's Zen, verses 9-11).
What's wrong with raising ZeroDivisionError (not stopping the
exception in the first place)?

k
Jun 27 '08 #8
On Apr 24, 5:28*am, malkarouri <malkaro...@gmail.comwrote:
>
What's wrong with raising ZeroDivisionError (not stopping the
exception in the first place)?
Because when I use your module, call avg (or mean) without args, I
should see an error that says, "Hey, you have to pass at least one
value in!"

ZeroDivisonError doesn't mean that. It means I tried to divide by
zero. Naively, I don't see where I was dividing by zero (because I
don't remember how to calculate the mean---that's what your code was
for.)

ValueError does mean that I didn't pass the right kind of arguments
in. ValueError("No items specified") would be even clearer. (Or maybe
TypeError?)

In general, any exception thrown should be meaningful to the code you
are throwing it to. That means they aren't familiar with how your code
works.
Jun 27 '08 #9
Jonathan Gardner wrote:
On Apr 24, 5:28 am, malkarouri <malkaro...@gmail.comwrote:
>What's wrong with raising ZeroDivisionError (not stopping the
exception in the first place)?

Because when I use your module, call avg (or mean) without args, I
should see an error that says, "Hey, you have to pass at least one
value in!"

ZeroDivisonError doesn't mean that. It means I tried to divide by
zero. Naively, I don't see where I was dividing by zero (because I
don't remember how to calculate the mean---that's what your code was
for.)

ValueError does mean that I didn't pass the right kind of arguments
in. ValueError("No items specified") would be even clearer. (Or maybe
TypeError?)

In general, any exception thrown should be meaningful to the code you
are throwing it to. That means they aren't familiar with how your code
works.
This is Advice. Software Engineering's next door ;-)

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Jun 27 '08 #10
On 24 avr, 14:28, malkarouri <malkaro...@gmail.comwrote:
On Apr 24, 12:43 pm, Bruno Desthuilliers <bruno.42.desthuilli...@websiteburo.invalidwrote :

[...]
Not quite sure what's the best thing to do in the second case - raise a
ValueError if args is empty, or silently return 0.0 - but I'd tend to
choose the first solution (Python's Zen, verses 9-11).

What's wrong with raising ZeroDivisionError (not stopping the
exception in the first place)?
Because - from a semantic POV - the real error is not that you're
trying to divide zero by zero, but that you failed to pass any
argument. FWIW, I'd personnaly write avg as taking a sequence - ie,
not using varargs - in which case calling it without arguments would a
TypeError (so BTW please s/Value/Type/ in my previous post).

Jun 27 '08 #11
On 4/24/08, Jonathan Gardner <jg******@jonathangardner.netwrote:
On Apr 24, 5:28 am, malkarouri <malkaro...@gmail.comwrote:
>
What's wrong with raising ZeroDivisionError (not stopping the
exception in the first place)?
>


Because when I use your module, call avg (or mean) without args, I
should see an error that says, "Hey, you have to pass at least one
value in!"

ZeroDivisonError doesn't mean that. It means I tried to divide by
zero. Naively, I don't see where I was dividing by zero (because I
don't remember how to calculate the mean---that's what your code was
for.)

ValueError does mean that I didn't pass the right kind of arguments
in. ValueError("No items specified") would be even clearer. (Or maybe
TypeError?)

In general, any exception thrown should be meaningful to the code you
are throwing it to. That means they aren't familiar with how your code
works.
[source]|557def average(n, *ints):
|... return (sum(ints)+n) / (len(ints) + 1)
|...>
[source]|558average (1,2,3)
<5582
[source]|559average(3)
<5593
[source]|560average(1,2)
<5601
[source]|561average(0)
<5610
[source]|562average()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)

/usr/share/doc/packages/python-dateutil/source/<ipython consolein <module>()

TypeError: average() takes at least 1 argument (0 given)
Jun 27 '08 #12
member thudfoo wrote:
On 4/24/08, Jonathan Gardner <jg******@jonathangardner.netwrote:
>On Apr 24, 5:28 am, malkarouri <malkaro...@gmail.comwrote:
> >
What's wrong with raising ZeroDivisionError (not stopping the
exception in the first place)?


Because when I use your module, call avg (or mean) without args, I
should see an error that says, "Hey, you have to pass at least one
value in!"

ZeroDivisonError doesn't mean that. It means I tried to divide by
zero. Naively, I don't see where I was dividing by zero (because I
don't remember how to calculate the mean---that's what your code was
for.)

ValueError does mean that I didn't pass the right kind of arguments
in. ValueError("No items specified") would be even clearer. (Or maybe
TypeError?)

In general, any exception thrown should be meaningful to the code you
are throwing it to. That means they aren't familiar with how your code
works.

[source]|557def average(n, *ints):
|... return (sum(ints)+n) / (len(ints) + 1)
|...>
[source]|558average (1,2,3)
<5582
[source]|559average(3)
<5593
[source]|560average(1,2)
<5601
[source]|561average(0)
<5610
[source]|562average()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)

/usr/share/doc/packages/python-dateutil/source/<ipython consolein <module>()

TypeError: average() takes at least 1 argument (0 given)
--
http://mail.python.org/mailman/listinfo/python-list
It would also be usual to use floating arithmetic to ensure that the
mean of 1 and 2 was 1.5 rather than 1.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Jun 27 '08 #13
Steve Holden <st***@holdenweb.comwrote:
Ken wrote:
"Steve Holden" <st***@holdenweb.comwrote in message
[...]
def mean(*x):
total = 0.0
for v in x:
total += v
return v/len(x)
think you want total/len(x) in return statement
Yes indeed, how glad I am I wrote "untested". I clearly wasn't pair
programming when I wrote this post ;-)
Posting to comp.lang.python is pair programming with the entire
internet ;-)
--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Jun 27 '08 #14
Nick Craig-Wood wrote:
Steve Holden <st***@holdenweb.comwrote:
> Ken wrote:
>>"Steve Holden" <st***@holdenweb.comwrote in message
[...]
>>>def mean(*x):
total = 0.0
for v in x:
total += v
return v/len(x)

think you want total/len(x) in return statement
Yes indeed, how glad I am I wrote "untested". I clearly wasn't pair
programming when I wrote this post ;-)

Posting to comp.lang.python is pair programming with the entire
internet ;-)

+1 QOTW :)

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Jun 27 '08 #15
Lie
On Apr 25, 2:12*am, "bruno.desthuilli...@gmail.com"
<bruno.desthuilli...@gmail.comwrote:
On 24 avr, 14:28, malkarouri <malkaro...@gmail.comwrote:
On Apr 24, 12:43 pm, Bruno Desthuilliers <bruno.42.desthuilli...@websiteburo.invalidwrote :
[...]
Not quite sure what's the best thing to do in the second case - raise a
ValueError if args is empty, or silently return 0.0 - but I'd tend to
choose the first solution (Python's Zen, verses 9-11).
What's wrong with raising ZeroDivisionError (not stopping the
exception in the first place)?

Because - from a semantic POV - *the real error is not that you're
trying to divide zero by zero, but that you failed to pass any
argument. FWIW, I'd personnaly write avg as taking a sequence - ie,
not using varargs - in which case calling it without arguments would a
TypeError (so BTW please s/Value/Type/ in my previous post).
The problem with passing it as a sequence is, if you want to call it,
you may have to wrestle with this odd looking code:
avg((3, 4, 6, 7))

rather than this, more natural code:
avg(3, 4, 6, 7)

And FWIW, the OP asked if it is possible to pass variable amount of
arguments, avg is just a mere example of one where it could be used
not where it could be best used.

Nick Craig-Wood wrote:
Steve Holden <st...@holdenweb.comwrote:
> Ken wrote:
>>"Steve Holden" <st...@holdenweb.comwrote in message
[...]
>>>def mean(*x):
total = 0.0
for v in x:
total += v
return v/len(x)
>> think you want total/len(x) in return statement
> Yes indeed, how glad I am I wrote "untested". I clearly wasn't pair
programming when I wrote this post ;-)
Posting to comp.lang.python is pair programming with the entire
internet ;-)
No, actually it's pair programming with the readers of c.l.py (or more
accurately with the readers of c.l.py that happens to pass the said
thread).
Jun 27 '08 #16
Lie a écrit :
On Apr 25, 2:12 am, "bruno.desthuilli...@gmail.com"
<bruno.desthuilli...@gmail.comwrote:
(...)
>FWIW, I'd personnaly write avg as taking a sequence - ie,
not using varargs - in which case calling it without arguments would a
TypeError (so BTW please s/Value/Type/ in my previous post).

The problem with passing it as a sequence is, if you want to call it,
you may have to wrestle with this odd looking code:
avg((3, 4, 6, 7))

rather than this, more natural code:
avg(3, 4, 6, 7)
Possibly. Yet my experience is that, most of the time, such a function
will be called with an already existing sequence, so the most common
call scheme is

res = avg(some_sequence)

which is more natural than

res = avg(*some_sequence)

!-)

And FWIW, the OP asked if it is possible to pass variable amount of
arguments, avg is just a mere example of one where it could be used
not where it could be best used.
Indeed - but that's not what I was commenting on.
Jun 27 '08 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
14901
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) {...
35
2407
by: michael.casey | last post by:
The purpose of this post is to obtain the communities opinion of the usefulness, efficiency, and most importantly the correctness of this small piece of code. I thank everyone in advance for your...
16
3827
by: Peng Yu | last post by:
Hi, I'm wondering if there is a min function (in boost, maybe?) that accepts any number of arguments? std::min only accepts two arguments. If I want to get the minimum number out of many, I have...
0
6964
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7126
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
6842
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7330
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5434
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4559
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3070
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1378
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
262
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.