Python function functions

Source: Internet
Author: User


Function

    • Once the code has a regular repetition, write only once for the function to be used multiple times (called)

Functions that can be used:
    • Custom functions
    • Built-in functions: Document Https://docs.python.org/3/library/functions.html, which itself contains a number of useful functions that can be called directly, such as Max (), ABS ().
Call Function:
    • To know the name and parameters of a function
    • The number of parameters and the parameter type must be correct, otherwise reported TypeError errors, and an error message is given
    • Conversion of data type: Int (), float (), str (), BOOL ()

To define a function:
    • Define a function to use a def statement, write down the function name, parentheses, the arguments in parentheses, and a colon : , and then write the function body in the indent block, returning the function's return value with a return statement.
    • If there is no return statement, the result is returned after the function is executed, except that the result isNone,就是return。 
 1  #   Customize an absolute my_abs function as an example:  2  def   My_abs (x):  3  if  x >= 0:  4  return   x  5  else  :  6  return -X 
    • Parsing: If you have my_abs() saved the function definition as a abstest.py file, you can start the Python interpreter in the current directory of the file, from abstest import my_abs import the my_abs() function, and note the file abstest name (without the .py extension)
    • Null function: If you want to define an empty function that does nothing, you can use a pass statement: It pass can actually be used as a placeholder
    • Parameter check: isinstance ()
the code above #若传入是字符 ' s ' will error, add isinstance () to judge.
1 defmy_abs (x):2 if notisinstance (x, (int, float)):3 RaiseTypeError ('Bad operand type')4 ifX >=0:5 returnx6 Else:7 return-X
Parameters of the function
# calculates the second side of X def Power (x, N):     = 1     while n > 0:        = n-1        = S * x    return s

1 Position parameter : the corresponding parameter is passed in the corresponding position, the most used.

such as: Call Power (5, 2)

2 Default parameters: If you use a parameter frequently, you can set it to the default value.

Often calculated x2, the above function can be written as Def power (x, n=2), call directly writable power (5), the rest of the situation according to positional parameters processing.

#是必选参数在前, the default parameter is behind, otherwise the Python interpreter will error

#当函数有多个参数时, put the parameters of the change to the front, the change of the small parameters put behind. Parameters with small variations can be used as default parameters.

#定义默认参数要牢记一点: The default parameter must point to the immutable object! str, None such immutable objects, once created, the data inside the object cannot be modified. Because the object is not changed, it is not necessary to lock the object at the same time in a multitasking environment, and not to read a problem at the same time. When we are writing a program, if we can design a constant object, we try to design it as an immutable object.

1 #l Tiaogan Use and increase change2 defAdd_end (l=[]):3L.append ('END')4     returnL5 6>>>add_end ()7['END','END']8>>>add_end ()9['END','END','END']Ten  One #none of this invariant parameter to implement A defAdd_end (l=None): -     ifL isNone: -L = [] theL.append ('END') -     returnL

3 Variable parameters:

Variable parameter is the number of parameters passed in is variable, can be one, 2 to any, or 0. with *, variable parameters allow you to pass in 0 or any of the parameters, which are automatically assembled as a tuple when the function is called

Function: Pass variable parameters

#Calculate a2+b2+c2+ ...defCalc (numbers): Sum=0 forNinchNumbers:sum= SUM + N *Nreturnsum#assemble a list or tuple>>> Calc ([1, 2, 3])14>>> Calc ((1, 3, 5, 7))84#variable ParametersdefCalc (*numbers): Sum=0 forNinchNumbers:sum= SUM + N *Nreturnsum>>> Calc (1, 2)5>>>Calc ()#already have a list or a tupleNums = [1, 2, 3]calc (*nums)14

4 keyword Parameters:

Allows you to pass in 0 or any parameter with a parameter name , which is automatically assembled inside the function as a dict

                          action: pass arbitrary parameters to extend function functions

 def  person (name, age, **kw):  print   (name, age, kw)  >>> person ( " michael  "  , 30 30 {}  >>> person ( Span style= "COLOR: #800000" > " bob  "  , City= " beijing   " ) Bob  { "  City   ": "   Beijing   "} 
#已经有的传入
>>> extra = {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}>>> person(‘Jack‘, 24, **extra)name: Jack age: 24 other: {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}

5 named keyword parameters:

The caller of the function can pass in any unrestricted keyword argument. As for what is passed in, it needs to be checked inside the function kw .

#* The following parameters are treated as named keyword parameters and receive city and job as keyword parametersdefPerson (name, age, *, City, job):Print(name, age, City, job)#The named keyword argument must pass in the parameter name>>> person ('Jack', city='Beijing', job='Engineer') Jack24Beijing Engineer#there is already a mutable parameter in the function definition .defPerson (name, age, *args, City, job):Print(name, age, args, city, job)

6 parameter combinations

The order of the parameter definitions must be: required, default, variable, named keyword, and keyword parameters.

defF1 (A, B, c=0, *args, * *kw):Print('A ='A'B ='B'C ='C'args =', args,'kw =', kw)defF2 (A, B, c=0, *, D, * *kw):Print('A ='A'B ='B'C ='C'd ='D'kw =', kw)>>> F1 (1, 2) A= 1 b = 2 c = 0 args = () kw = {}>>> F1 (1, 2, c=3) A= 1 b = 2 c = 3 args = () kw = {}>>> F1 (1, 2, 3,'a','b') A= 1 b = 2 c = 3 args = ('a','b') kw = {}>>> F1 (1, 2, 3,'a','b', x=99) A= 1 b = 2 c = 3 args = ('a','b') kw = {'x': 99}>>> F2 (1, 2, d=99, ext=None) A= 1 b = 2 c = 0 d = HP = {'ext': None}#The most amazing thing is that through a tuple and dict, you can also call the above function:>>> args = (1, 2, 3, 4)>>> kw = {'D': 99,'x':'#'}>>> F1 (*args, * *kw) a= 1 b = 2 c = 3 args = (4,) kw = {'D': 99,'x':'#'}>>> args = (1, 2, 3)>>> kw = {'D': 88,'x':'#'}>>> F2 (*args, * *kw) a= 1 b = 2 c = 3 D ='x':'#'}

Summary

Python's functions have a very flexible parameter pattern, which allows for simple invocation and very complex parameters to be passed.

Default parameters must be used immutable objects, if it is a mutable object, the program will run with a logic error!

Be aware of the syntax for defining mutable parameters and keyword parameters:

*argsis a variable parameter, and args receives a tuple;

**kwis a keyword parameter, kw receives a dict.

And how to pass in the syntax for variable and keyword arguments when calling a function:

Variable parameters can be directly passed func(1, 2, 3) in:, you can first assemble a list or a tuple, and then pass in *args : func(*(1, 2, 3)) ;

Keyword parameters can be directly passed in: func(a=1, b=2) , you can first assemble dict, and then pass in **kw : func(**{‘a‘: 1, ‘b‘: 2}) .

It *args is customary to use and **kw be python, but it is also possible to use other parameter names, but it's best to get used to idioms.

The named keyword parameter is used to limit the name of the parameter that the caller can pass in, as well as providing a default value.

Define a named keyword parameter do not forget to write a delimiter without a mutable parameter * , otherwise the positional parameter will be defined.

Python function functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.