"Eighth" in Python Learning: function basics in Python

Source: Internet
Author: User

1. Preface

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.

2. Definition of functions

The following rules apply when defining a function:

    • 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, and the parentheses can be used to define the 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 函数名(参数1,参数2,参数3,...):                       '''注释'''    函数体    return 返回的值
3. Invocation of functions

Function call: function name plus parentheses

    1. Find the name first.
    2. Calling code by name
4. Parameters of the function

Formal parameter types that can be used when calling a function:

    • Position parameters
    • Keyword parameters
    • Default parameters
    • Indefinite length parameter
Position parameters

Positional parameters, also called required parameters, must be passed to the position parameter when the function is called, and must be passed in in the correct order and in the same quantity.

def func(name,age):    print ('我叫%s,我今年%s岁了' %(name,age))    func('张三',18)#输出'我叫张三,我今年18岁了'
Keyword parameters

In the form of parameter name = parameter value as the incoming function is called a keyword parameter, the order of the parameters is not consistent with the declaration when using the keyword argument, because the Python interpreter can match the parameter value with the name of the argument.

def func(name,age):    print ('我叫%s,我今年%s岁了' %(name,age))    func(age=18,name='张三')#输出'我叫张三,我今年18岁了'
Default parameters

When defining a function, if the value of some parameters does not change frequently, you can set it as the default parameter, and if you pass an argument to the default parameter when the function is called, the default argument is used if the argument is passed.

# age为默认参数,默认为18def func(name,age=18):    print ('我叫%s,我今年%s岁了' %(name,age))func(age=28,name='张三')    #age传了28,则使用传来的28func(name='李四')          #age没有传参,则使用默认的18#输出'我叫张三,我今年28岁了''我叫李四,我今年18岁了'
Indefinite length parameter

If you need to pass a lot of arguments to the function, and when the function declaration is not sure how many parameters will be passed in the call, in this case, the variable length parameter will be used
The indefinite length parameters are received using *args and **kwargs:

    • The variable *args of the Gathan (*) is used to receive all parameters except the key-value pair and is saved as a tuple;
    • The variable **kwargs of the double star (* *) is used to receive the named parameter, which is the parameter of shape such as Key=value, and is saved in dictionary form;
def func(a,b,*args,**kwargs):    print(a)    print(b)    print(args)    print(kwargs)func(1,2,3,4,5,6,w=7,j=8)#输出12(3, 4, 5, 6){'w': 7, 'j': 8}
5. Case studies

Write a summation function that calculates the sum of all the parameters passed in by the user and cannot limit the number of parameters passed in by the user

def sum(*args):    res = 0    for i in args:        res += i    return resprint(sum(1,2)) print(sum(1,2,3,4,5,6,7,8,9))   #输出3 45

"Eighth" in Python Learning: function basics in Python

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.