function with variable arguments

Dan Sommers me at privacy.net
Fri May 13 06:57:53 EDT 2005


On 13 May 2005 02:52:34 -0700,
"Xah Lee" <xah at xahlee.org> wrote:

> i wanted to define a function where the number of argument matters.
> Example:

> def Range(n):
>     return range(n+1)

> def Range(n,m):
>     return range(n,m+1)

> def Range(n,m,step):
>     return range(n,m+1,step)

> this obvious doesn't work. The default argument like
> Range(n=1,m,step=1) obviously isn't a solution.

> can this be done in Python?

Assuming you're doing something more interesting than wrapping range:

    def Range( start, stop = None, step = 1 ):
        if stop == None: # i,e., we only got one argument
            stop = start
            start = 1
        # rest of function goes here....

HTH,
Dan

-- 
Dan Sommers
<http://www.tombstonezero.net/dan/>



More information about the Python-list mailing list