My Python introductory notes (13)

Ten chapters, the function (a)


If the implementation is hard to explain, it's a bad idea.——The Zen of Python


  Program should be broken down into smaller parts, there are three main methods. Function (function) code is like building blocks, can be used repeatedly, using the object (Object), each part of the program can be described as self-contained unit. Module (Module1) is a separate file for each part of the program. Tissue function is good, it can be reused, or used to implement a single code segment associated function. Function modules of the application can be improved, and code reuse.

First, create and call functions

  1. Create a function

  Create a function called defined functions also can be understood as a tool creates a particular purpose. Use the keyword def achieve its syntax is as follows:

  def functionname([parameterlist]):

       [‘’’comments’’’]

       [functionbody]

  f unctionname: function name is used when calling the function

  paramenterlist: an optional parameter that specifies the transfer function parameters, if there are multiple parameters, separated by commas between the parameters, if not specified, it means that the function has no parameters. When calling, nor specified function.

  comments: optional parameter, expressed as a function specify annotation, content usually is a functional annotation of the function, role and other parameters to be passed, it is possible to provide a friendly tips and help content for the user.

  functionbody: an optional parameter that specifies the function, i.e. after the function is called, the function code to be executed, if the function returning value, may be used to return the return statement

  When the function has no parameters, it must remain an empty pair of parentheses, otherwise it will error. When you define a function, if the "comments" parameter is specified, then the function call, the name and the left parenthesis when the input function will display help information about that function. Function body "functionbody" and the comment "comments" in relation to the def keyword must retain a certain indentation.

  2. Call function

  Call a function that executes the function, if the function is trying to create some kind of understanding for the creation of a tool to use, then the function call is equivalent to using the tool, its syntax is as follows:

  functionname([paramentersvalue])

  functionname: function name, function name to be called, must be already created

  paramentersvalue: Optional parameter values for each parameter specified, if the need to pass a plurality of parameter values, separated by commas the individual parameter values, if the function has no parameters, directly to write a pair of parentheses.

. 1 DEF filterchar ( String ):
 2      "" "
 . 3      : param String : filtering dangerous characters (such as sucker), and outputs the filtered results
 . 4      : return : no return value
 . 5      " ""
 . 6      Import Re
 . 7      pattern = R & lt ' (sucker) | (sand sculpture users) ' 
8      Sub = re.sub (pattern, ' ** ' , String )
 9      Print (Sub)
 10 the About = ' I come from the far right of the sand sculpture, but not sucker ' 
11  filterchar (the About )
 12  output:
 13 I'm from the rightmost sand sculpture, but not ***

  3.pass empty statement

  There are a pass statement in Python, it represents the empty statement, it does not do anything, generally played the role of placeholder. For example, create a function, but we do not know what function to achieve this function, you can use this time to fill the function of the body pass statement, it said that "the future will write", for example:

1 def dunc():
2     #pass

  In python3 allowed used wherever an expression is ... (3 consecutive dot) code is to be omitted, since their ellipses do nothing, therefore, can be used as an alternative to pass statement.

1 def func():
2     ...

 Second, the parameters are passed

  When calling the function, in most cases, the data transfer relationship between the calling function and the called function, which is to have a function as a parameter. Action function parameter is used to pass data to the function, the function using the received data of the specific operation processing.

  

  

  1. formal and actual parameters

  When using the function, it is often used in the form of parameters (parameters) and actual parameters (arguments). And the difference parameter arguments.

  Formal parameters: In the definition of the function, the function name in parentheses behind the parameter is "formal parameters", also known parameter.

  Actual parameters: When calling a function, the function name in parentheses behind parameter is "actual parameter", that is, provided to the caller of the function parameters of the function called actual parameters, also called argument.

  Depending on the types of arguments can be divided into the value of the argument passed to the parameter , and the arguments passed to the parameter referenced in both cases. Wherein, when the real time parameter immutable object, the value passed is performed; when the argument is a variable object, it is passed by reference. In fact, after the difference between the value of the basic transmission and is passed by reference, a value passed, changing the value of the parameter, the value of the argument of the same; and after passing by reference, changing the value of the parameter, the value of the argument is also changed together .

  Argument function definition list parameter is a parameter, the parameter passed in the function call is the argument.

  2. position parameters

  Location parameters also known mandatory parameter, the function must be passed in the correct order, the number and position, i.e. when calls must be defined is the same.

    1 The number must be consistent with the definition

     When calling the function, parameter specifies the actual amount must be consistent with the shape parameter amount, otherwise it will throw a TypeError exception, suggesting that the lack of the necessary positional parameters. For example: define a function that has three parameters, but at a time when the call pass two parameters, an error is prompted.

    2. The position must be consistent with the definition:

  When calling the function, the actual parameter specified location must be consistent with the parameter position, otherwise it will produce two results:

    1. TypeError exception is thrown,

    2. produce results inconsistent with the expected results (when calling function must determine a good location, otherwise prone to bug, and not easily found)

  3. keyword arguments

  Keyword parameter is used to determine the parameter name parameter value input. When the argument is specified by the way, no longer needs to be consistent with the formal parameters of the position, as long as the parameter name to write correctly. This prevents the user the trouble to keep in mind the parameters of position, making calls and parameters passed function more flexible.

  4. Set the default value for the parameter

       When you call the function, if not a given argument will throw an exception, that is, when defining the function, directly specify a default value in the form of parameters. Thus, when no parameters are passed, directly using a defined function to set the default values. The syntax is as follows:

def functionname(…,[parameter1=defaultvalue]):
    [functionbody]

  functionname: function name is used when calling the function

  parameter1 = defaultvalue: an optional parameter that specifies the parameters passed to the function, and set the default value for the parameter defaultvalue

  functionbody: an optional parameter to the function code specifies the function body, i.e., after the function is called, to perform

  When you define a function, specify the default parameter must be the last of all parameters, or will cause a syntax error. In addition, in Python, you can use the "function name _defaults_" the current value of the default value of the parameter viewing function, the result is a tuple. When using variable objects as the default function parameters, multiple calls may result in the unexpected. Examples are as follows:

. 1  DEF demo (obj = []): # -defined function and specify a default value for the parameter obj 
2      Print ( " obj values: " , obj)
 . 3      obj.append (. 1 )
 . 4 demo ()    # call demo function 
5  outputs:
 . 6 obj values: []
1 Demo ()    # the call to 
2  Output:
 . 3  obj values: []
 . 4 obj values: [1]

  This is obviously not the desired result, to prevent this, it is best to use None as the default value of the variable object, this time also need to check the code. Modified as follows:

. 1  DEF Demo (obj = None): # defined function with the default values for the parameter obj 
2      IF obj == None:
 . 3          obj = []
 . 4      Print ( " obj values: " , obj)
 . 5      obj.append (. 1 )
 . 6 demo ()    # call demo function 
. 7 demo ()    # the call to 
8  outputs:
 . 9  obj values: []
 10 obj values: []

  Defining a function, in the form of default values ​​for the parameter set to keep in mind: the default parameter must point to an immutable object.

   The variable parameter

  In Python, variable parameters may also be defined. Also known as variable length parameter variable parameters, i.e. the actual parameter passed in the function may be any number, in the definition of the variable parameters, there are two main forms: a * parameter, the other is ** parameter.

  1.*parameter

  This form represents any number of actual parameters received and putting it in a tuple. For example, the definition of a function, let it be received at any of a plurality of actual parameter.

. 1  DEF lovenum (* NUM):
 2      Print ( ' \ n-I like numbers have: ' , End = '  ' )
 . 3      for Item in NUM:
 . 4          Print (Item, End = "")
 . 5 lovenum ( ' 220 ' )
 . 6 lovenum ( ' 220 ' , ' 284 ' , ' 26 is ' )
 . 7 lovenum ( ' 220 ' , ' 284 ' ,' 1210 ' , ' 1184 ' )
 8  Output:
 9  I like numbers are:
 10 220 
 . 11  my favorite numbers are:
 12 is 220 284 26 is 
 13 is  my favorite numbers are:
 14 220 284 1210 1184

  If you want to use an existing list variable as a function of the parameters, can be added to the list before the name of "*"

. 1  DEF lovenum (* NUM):
 2      Print ( ' \ n-I like numbers have: ' )
 . 3      for Item in NUM:
 . 4          Print (Item, End = '  ' )
 . 5 List1 = [22,26,220,284 ]
 . 6 lovenum (* List1)
 . 7  output:
 8  I like numbers are:
 . 9 22 is 26 is 220 284

  2.**parameter

  This represents the actual parameters received any form of a plurality of explicit assignment, and put them in a dictionary , an example, the definition of a function, so that it could receive any more explicit assignment actual parameters, for example:

. 1  DEF lovenum (** NUM):
 2      Print ()
 . 3      for num1, num2 in num.items ():
 . 4          Print (num1 + ' like numbers are: ' + num2)
 . 5 lovenum (rain students Ni = ' 1210 ' , Shu snow students = ' 1184 ' )
 6  output:
 7 rain Ni students like numbers are: 12.1
 . 8 Shu snow students like figures is: 1184

  If you want to use a dictionary already exists as a function of the variable parameters, you can add "***" in front of the name of the dictionary. Examples are as follows:

. 1  DEF lovenum (** NUM):
 2      Print ()
 . 3      for num1, num2 in num.items ():
 . 4          Print (num1 + ' like numbers are: ' + num2)
 . 5 dict1 = { ' rain Ni students ' : ' 1210 ' , ' Shu snow students ' : ' 1184 ' , ' cream sequence ' : ' 220 ' }
 . 6 lovenum (** dict1)
 . 7  output:
 8Students like rain rainbow numbers are: 12.1
 9 Shu snow students like figures are: 1184
 10 frost like sequence number is: 220

Guess you like

Origin www.cnblogs.com/1210x1184/p/11117897.html