How can I define a function with default parameter values and optional parameters in Python?

前端 未结 4 1522
别跟我提以往
别跟我提以往 2021-01-14 23:29

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):
   d         


        
4条回答
  •  孤街浪徒
    2021-01-14 23:47

    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.

提交回复
热议问题