Python Learning note 8-python function

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. 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.

First, define the 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. 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] End Function, optionally returning a value to the caller. Return without an expression is equivalent to returning None.

Grammar:

def functionname (parameters): "Function _ Document String" Function_suite return [expression]

By default, parameter values and parameter names are matched in the order defined in the function declaration.

Second, function call

Defines a function that gives the function a name, specifies the parameters contained in the function, and the code block structure.

Once the basic structure of this function is complete, you can execute it from another function call or directly from the Python prompt.

def xaddy (x, y): #函数定义 return x+yprint Xaddy #函数调用

Execution results are

3

Third, parameter transfer

All parameters (independent variables) are passed by reference in Python. If you modify the parameters in the function, the original parameters are changed in the function that called the function. For example:

def a (x): X.append (' ADFA ') return xy=list (' abcdef ') print yprint A (y) print y

Execution results are

[' A ', ' B ', ' C ', ' d ', ' e ', ' F '] [' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' ADFA '] [' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' ADFA ']

Here, the parameter X in the function receives the address that the variable y points to, the memory address stores the value ([' A ', ' B ', ' C ', ' d ', ' e ', ' f ']) in the function body, the function execution x.append (' ADFA ') is actually appending an element at the end of the list Y, Take another look at the following example:

def a (x): X=list (' 1234 ') return xy=list (' abcdef ') print yprint A (y) print y

Execution results are

[' A ', ' B ', ' C ', ' d ', ' e ', ' F '] [' 1 ', ' 2 ', ' 3 ', ' 4 '] [' A ', ' B ', ' C ', ' d ', ' e ', ' F ']

In the above example, the formal parameter of function A receives the memory address passed by the argument y, in the function body, assigns the value to x, so the value of x is changed, and the value of argument y does not change.

Iv. parameters

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

Required Parameters

Named parameters

Default parameters

Indefinite length parameter

1. Required Parameters

The required parameters must be passed into the function in the correct order. The number of calls must be the same as when declared.

Call the A () function, you must pass in a parameter, or a syntax error will occur:

def a (x): Print xy=list (' abcdef ') A ()

Execution results are

Traceback (most recent): File "E:\Note\Python\test.py", line 4, in <module> A () typeerror:a () takes ex actly 1 argument (0 given)

2. Named parameters

Named arguments and function calls are closely related, and the caller determines the passed-in parameter value with the name of the parameter. You can skip arguments that do not pass or sequence the arguments, because the Python interpreter can match parameter values with the name of the argument.

def a (name,age): print ' name: ' +name+ ', Age: ' +agea (age= ', name= ' Zhangsan ')

Execution results are

Name:zhangsan,age:19

3. 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.

def a (name,age= '): print ' name: ' +name+ ', Age: ' +agea (' Zhangsan ')

Execution results are

Name:zhangsan,age:20

When defining a function, to use the default parameters, you should put the default arguments to the end and put the prerequisites in front of it, otherwise the system cannot determine whether the arguments that were given to the function were supplied to the required parameters or the default parameters.

4. Indefinite length parameter

You may need a function that can handle more arguments than was originally declared. These parameters are called indeterminate length parameters, and are not named when declared, unlike the above 2 parameters. The basic syntax is as follows:

def functionname ([Formal_args,] *var_args_tuple): "Function _ Document String" Function_suite return [expression]
def a (x,*y): Print x Print ya (ten) print ' A (10,20) print ' A (10,20,30)

Execution results are

10 () 10 (20,) 10 (20, 30)

As you can see, the type of an indeterminate parameter is a tuple, which can be used in the body of a function as if it were a normal tuple.

Variable names with an asterisk (*) will hold all unnamed variable arguments. Choose not to send more parameters can also.

When defining an indefinite length parameter, precede the formal parameter with a ' * ', the type of the parameter is a tuple, and if you add two ' * ', the type of the parameter is a dictionary.

def a (x,**y): Print x Print ya (ten) print ' A (10,a=20) print ' A (10,a=20,b=30)

Execution results are

10{}10{' a ': 20}10{' a ': +, ' B ': 30}

Five, anonymous function

Use lambda keywords to create small anonymous functions. This function is named after the standard procedure for declaring a function with DEF is omitted.

A lambda function can receive any number of arguments but can only return the value of an expression, and can only contain commands or multiple expressions.

Anonymous functions cannot call print directly, because lambda requires an expression.

The lambda function has its own namespace and cannot access parameters outside its own argument list or in the global namespace.

Although the lambda function appears to be only a single line, it is not equivalent to a C or C + + inline function, which is designed to call small functions without consuming stack memory to increase operational efficiency.

Syntax: The syntax for a lambda function contains only one statement, as follows:

Lambda [arg1 [, Arg2,..... argn]]:expression
Sum=lambda a,b:a+bprint sum (10,20) print sum (100,200)

Execution results are

30300

Six, return statement

Return statement [expression] exits the function, optionally returning an expression to the caller. A return statement without a parameter value returns none.

This article is from the "Raffaele" blog, make sure to keep this source http://raffaele.blog.51cto.com/6508076/1570948

Python Learning note 8-python function

Related Article

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.