2

I want to define a function to which the input parameters can be omitted or have a default value.

I have this function:

def nearxy(x,y,x0,y0,z):
   distance=[]
   for i in range(0,len(x)):   
   distance.append(abs(math.sqrt((x[i]-x0)**2+(y[i]-y0)**2)))
   ...
   return min(distance)

I want make x0 and y0 have a default value, and make z optional if I don't have a z value.

How can I do that? Thank you.

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
wuwucat
  • 2,523
  • 8
  • 23
  • 26

4 Answers4

6

You can't make function arguments optional in Python, but you can give them default values. So:

def nearxy(x, y, x0=0, y0=0, z=None):
    ...

That makes x0 and y0 have default values of 0, and z have a default value of None.

Assuming None makes no sense as an actual value for z, you can then add logic in the function to do something with z only if it's not None.

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
  • 1
    Having `None` as a default argument makes sense cause the default argument object is persistent between calls of the function. See http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument – Christoph Feb 07 '13 at 16:42
4
def nearxy(x, y, x0 = 0, y0 = 0, z = None):
   ...

Check if z is None to see if it has been omitted.

Charles Salvia
  • 52,325
  • 13
  • 128
  • 140
3

give default values to x0,y0 like this and if z is optional also :

def nearxy(x,y,x0=0,y0=0,z=None):
   distance=[]
   for i in range(0,len(x)):   
   distance.append(abs(math.sqrt((x[i]-x0)**2+(y[i]-y0)**2)))
   if z is not None:
        blah blah
   return min(distance)

call :

nearxy(1,2)

if you want only toassign z :

 nearxy(1,2,z=3)

....

hope this helps

sancelot
  • 1,905
  • 12
  • 31
2

To specify a default value, define the parameter with a '=' and then the value.

An argument where a default value is specified is an optional argument.

For example, if you wanted x0,y0, and z to have default values of 1,2,3:

def nearxy(x,y,x0=1,y0=2,z=3):
   distance=[]
   for i in range(0,len(x)):   
       distance.append(abs(math.sqrt((x[i]-x0)**2+(y[i]-y0)**2)))
   ...
   return min(distance)

See http://docs.python.org/2/tutorial/controlflow.html#default-argument-values for more.

Moshe
  • 9,283
  • 4
  • 29
  • 38