Python Note 4-functions

Source: Internet
Author: User

Functions are well-organized, reusable pieces of code that are used to implement a single, or associated function.

Functions can improve the modularity of the application, and the reuse of the code. You already know that Python provides a number of built-in functions, such as print (). But you can also create your own functions, which are called user-defined functions.

Define a function

You can define a function that you want to function, and here are the simple rules:

    • The function code block begins with a def keyword followed by the function identifier name and parentheses ().
    • Any incoming parameters and arguments must be placed in the middle of the parentheses. Parentheses can be used to define parameters.
    • The first line of the function statement can optionally use the document string-for storing the function description.
    • The function contents begin with a colon and are indented.
    • return [expression] ends the function, optionally returning a value to the caller. Return without an expression is equivalent to returning None.
Grammar
def functionname (Parameters):   #定义一个函数, functionname is a function name, function name cannot   be repeated " Function _ document string "     function_suite                 #函数体    return [expression]            #return返回值, if there is no return, Then the function returns to None
Parameters

The following are the formal parameter types that can be used when calling a function:

    • Position parameters
    • Default parameters
    • Keyword parameters
    • Indefinite length parameter (variable parameter)
Position parameters

Positional parameters must be passed into the function in the correct order . The number of calls must be the same as when the Declaration was made, and the positional parameter is required.

To call the plus function, you need to pass in 2 arguments, or you can report a syntax error, as follows:

def Plus (x, y):   # function name Plus, formal parameter: x, y, simply the parameter    print(x+y)    #  function Body, print the value of the X+y Plus (3, 4)       # function calls, 3 and 4 are arguments, which is the passed in parameter, the result is: 7

The number of arguments passed in the error, as follows:

def Plus (x, y    ): Print (x+y) plus (3, 4, 5) The error message is  as follows: " e:/python_workspace/base-code/day4/function my.py "  in <module>    Plus (3, 4, 52 positional arguments but 3 were given

The parameters are not passed in the correct order, and the results are printed as follows:

def Plus (name, age):     Print (name, age) plus ('lhl')       # Name=12,age=lhl, obvious entry is illegal
Positional Parameters-keyword pass-through

When calling a function using positional parameters, if you have more than one positional parameter, you can not remember which location to pass which to do, you may use the name of the positional parameter to specify the call, as follows:

#There are multiple positional parameters, which may be more and more, when using fixed positional parameters, cannot remember or pass the wrong position, you can use the name of the positional parameter to specify the call, called the keyword parameterdefPlus (name, age, sex, city, phone, money, color, time):Print(name, age, sex, city, phone, money, color, time) plus ('Zhangsan', 18,'Mans', color='Black', money=44444, Time=time.time (), phone=13400000000,city='Beijing')
execution result display corresponds to function parameter position:ZhangsanBeijing 13400000000 44444 Black 1497020260.7982826
Default parameters

When a function is called, the value of the default parameter is considered to be the default value if it is not passed in. So even if you do not pass this parameter in the call, it also has a value, the default parameter is not required, as follows:

def plus (name, sex, age=18):  #Agedefault parameter, default value is    print(name, sex, age) Plus ('zhangsan','man')       #  When the function is called, the value of age is not entered, and the default value is 18
Execution Result:
Zhangsan Mans 18

When the function is called, a value is passed to the default parameter, and the default parameter is followed by the position parameter, as follows:

def plus (name, sex, age=18):  #Agedefault parameter, default value is 18,age must be located after position parameter    print  (Name, sex, age) plus ('zhangsan' man', age=28)       # When the function is called, enter the value of age, the default is the input value
Execution Result:
Zhangsan Mans 28

When the function is called, the default parameter is preceded by the position parameter, and the syntax error is reported as follows:

defPlus (name, age=18, sex):#The default parameter for the age bit, the default value is 18,age must be located in the position parameter sex before the syntax error    Print(name, sex, age) plus ('Zhangsan','Mans')#The value of the default age is not entered when the function is calledThe error message is as follows: File"e:/python_workspace/base-code/day4/function my.py", line 67defPlus (name, age=18, sex):#The default parameter for the age bit, the default value is 18,age must be located in the position parameter sex before the syntax error^Syntaxerror:non-default argument follows default argument
Non-fixed parameters:

The above two positional parameters and the default parameters are the number of parameters is fixed, if I am a function, the parameters are not fixed, I do not know the future of this function will expand into what kind of, may be more and more parameters, this time if the fixed parameters, then the program is not good expansion, then you can use non-fixed parameters, There are two types of non-fixed parameters, one is a variable parameter and one is a keyword parameter.

Variable parameters:

Variable parameters are received with *, the number of arguments to pass after the number of passes, if the positional parameters, default parameters, variable parameters used together, the variable parameter must be in the position parameter and the default value parameter. Variable parameters are also non-mandatory.

defPost (*args):#when the number of arguments is not fixed, use *args variable parameter, parameter group, return result is tuple, also be non-required parameter    Print(args)#The printed result is a tuple: (' 001 ', ' login ', ' post '), the function has no return value, the return value is NonePost ()#A tuple that calls a function, does not pass arguments, prints an empty resultPrint(Post ('001','Login','Post') ) Execution Result: () ('001','Login','Post') None

Variable parameters are used with positional parameters, default parameters, as follows:

#variable parameters are received using *, * variable parameter name, must be placed after position parameter, default parameter, default parameter must be placed after position parameterdefPlus (name, sex, age=18, *args):Print(name)Print(Sex)Print(age)Print(args) plus ('Zhangsan','Mans','Black', 44444, 13400000000,'Beijing')#default parameters can not be passedExecution Result: Zhangsanmanblack (44444, 13400000000,'Beijing')
Keyword parameters:

Keyword parameters use * * To receive, the following parameters are not fixed, unlimited length, can also be used with positional parameters, default parameters, variable parameters, keyword parameters must be in the last side.

With keyword arguments, you must use the keyword argument when calling. Keyword parameters are also non-mandatory. As follows:

def Other (**kwargs):  # keyword parameter, incoming value passed in Key=value way, return result is dictionary type, also is non-required parameter    print  (Kwargs) Other (name='byz', age=18) execution result: {'  Name'byz' age': 18}

Used with positional parameters, default parameters, and variable parameters, as follows:

defOther (name, age, sex='male', *args, **kwargs):#keyword parameter, the passed in value is passed through the Key=value method, the returned result is the dictionary type, also is the non-required parameter    Print(name)Print(age)Print(Sex)Print(args)Print(Kwargs) Other ('Zhangsan', 24,'Red','Sun', city=,'Beijing', score=99) Execution Result: Zhangsan24Red ('Sun', 110){' City':'Beijing','score': 99}
Return statement

Return statement [expression] exits the function, optionally returning an expression to the caller. A return statement without a parameter value returns none. The previous example does not demonstrate how to return a value, and the following example tells you how to do it:

def sum (ARGS1, ARGS2):     = args1 + args2    print('total:')  #  The value of total is printed in the function     return total            # function returns total, if the input args1, args2 bit int type, The function returns an int, and if the bit int+float is entered, the result is a floatprint(sum (13.125.125.1
Global variables and local variables

Variables defined inside a function have a local scope, which defines the owning global scope outside of the function.

Local variables can only be accessed within their declared functions, while global variables are accessible throughout the program. Global variables if you want to modify in the function, you need to add the Global keyword declaration, if it is a list, dictionary and collection , you do not need to add the global keyword, directly can be modified, as follows:

Name ='Marry'  #String Global Variablesnames = []#List Global VariablesPrint(name)Print(names)defTest ():GlobalName#Modifying the value of a global variable-name requires declaring the name as all variables with the global keywordName ='Sriba'      #Modify the value of the global variable nameNames.append (name)#Modifying the value of a global variable names    returnnamestest ()Print('after modification', name)Print('names after modification', names) execution result: marry[] modified Sriba after modification names ['Sriba']

Modify the value of the global variable list type as follows:

names = [1, 2, 3, 4]#List Global VariablesPrint(names)defTest (): Names= ['a','b','C','D']#Modifying the value of the global variable names does not need to be directly modified with the Global keyword declaration    returnnamesPrint('names after modification:', Test ()) Executes the result: [1, 2, 3, 4] Names after modification: ['a','b','C','D']

Subsequent recursive calls ~ ~ ~

Python Note 4-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.