Python Function Basics

Source: Internet
Author: User

Function

L functions are well-organized, reusable code snippets for single or related functions

The L function can improve the modularity of the application and the reuse of the code. Python provides a number of built-in functions, or you can create your own functions, which are called user-defined functions

L function Classification: Built-in functions, custom functions

l do not use functions: Unclear organizational structure, code redundancy, inability to manage uniformly and difficult to maintain

First, define the function

L function code block begins with def keyword followed by function identifier name and parentheses ()

L any incoming parameters and arguments must be placed in the middle of the parentheses, between parentheses can be used to define the parameters

L define three forms of a function: No parameter (performs only a few actions), has a parameter (executes the corresponding logic according to the arguments passed in), an empty function (design code structure)

The first line of the L function can optionally use a document string to hold function descriptions

L function content starts with a colon, and indents

L return[expression] End Function, optionally returning a value to the caller. Return without an expression is equivalent to returning none

Grammar:

def function name (parameter list):

function body

Instance:

def hello ():    print (' Hello world! ') Hello ()

Second, return statement

The return [expression] statement is used to exit the function, optionally returning an expression to the caller. Return statement with no parameter value returns none

L return None when a function does not return, equivalent to return none

L return with a value returns the value without a data type limit

L Return with multiple values returns a single tuple

L when to have return value:

Call the function, after a series of operations, finally to get a definite result, you must have a return value

Usually a parameter function needs a return value, and the input parameter is computed to get a final result.

L When do not need to have return value:

Call the function, just perform a series of operations, and finally do not need to get any results, there is no need to have a return value

Normally no parameter function does not need to have a return value

Instance:

def my_sum (ARG1,ARG2): Total    = arg1 + arg2    return totalres = My_sum (10,20) print (res)

Iii. form of a function call

1, statement form, Example: Foo ()

2. Expression form, example: Res=len (' Hello ')

3. As a parameter of another function, example: Range (len (' Hello '))

Iv. parameters of the function

The parameters of the L function are divided into two types:

Formal parameters: arguments in a function

Argument: The value provided to the function call

L parameter Assignment method:

1. Positional parameters: Parameters defined in left-to-right order, the number of calls must be the same as when declared

def foo (x, y):    print (×)    print (y) foo (ON)

2. Keyword parameter: defined as parameter name = parameter value, the order of parameters can be inconsistent with declaration. Note that the key argument must be to the right of the positional argument and cannot repeat the value for the same parameter

def foo (x, y):    print (×)    print (y) foo (y=2,x=1)

3. Default parameters: When a function is called, default parameters are used if no arguments are passed. It is important to note that the default parameter must be to the right of the positional parameter and should normally be defined as an immutable type

def foo (name,age,sex= ' Male '):                   #在定义阶段就已经为形参赋值了    print (name,age,sex) foo (' Zhangsan ', age=18) foo (' Lisi ', age= Foo (' Wangwu ', 21,sex= ' female ')                   #也可以为默认参数赋值

4, variable length parameter: For the argument when the length of the definition is not fixed, the parameter should be found from the angle of the parameters can receive variable length arguments, this is the variable length argument (formal parameter). Use *args for positional parameters, use **kwargs for keyword parameters

def foo (X,y,*args):                             The variable name of the #加了 * will hold all the unnamed variable arguments. If the parameter is not specified when the function is called, it is an empty tuple    print (x)    print (y)    print (args) foo (1,2,3,4,5,6) #执行结果如下: 12 (3, 4, 5, 6)
def foo (X,y,**kwargs):                          #加了 * * variable names hold all unnamed variable arguments. If the parameter is not specified when the function is called, it is an empty dictionary    print (x)    print (y)    print (Kwargs) foo (x=1,y=2,z=3,a=4,b=5,c=6) #执行结果如下: 12{' z ': 3, ' A ': 4, ' B ': 5, ' C ': 6}

Extended usage:

def foo (X,y,*args): Print    (x)    print (y)    print (args) foo (1,2,* (3,4,5,6))                             #实际是: *args = * (3,4,5,6), The result is args = 3,4,5,6. You can simply disassemble and return to the original # execution results are as follows 12 (3, 4, 5, 6)
def foo (X,y,**kwargs): Print    (x)    print (y)    print (Kwargs) foo (x=1,y=2,**{' z ': 3, ' a ': 4, ' B ': 5, ' C ': 6}) # The execution results are as follows: 12{' Z ': 3, ' a ': 4, ' B ': 5, ' C ': 6}

5, named keyword parameter: * After the parameter defined, must be passed the value (except for the default value), and must be in the form of a keyword argument to pass the value

def foo (*args,y):    print (args)    print (y) foo (1,2,3,4,5,y=6)

V. Function objects

Functions are the first class of objects, that is, functions can be passed as data

1, can be assigned value

def foo ():    print (' Hello world! ') f = foof ()

2, can be passed as a parameter

def foo ():    print (' Hello world! ') def wrapper (func):    func () wrapper (foo)

3, can be used as a function of the return

def foo ():    print (' Hello world! ') def wrapper (func):    return funcres = wrapper (foo) print (res)

4. Elements that can be used as container types

def foo ():    print (' Hello world! ') Dict = {    ' func ': Foo}print (dict) dict[' func '] ()

Python Function Basics

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.