Python's Strongest King (9)--function

Source: Internet
Author: User
Tags variable scope

1.Python function

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):    " Function _ Document string "    function_suite   return [expression]

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

Instance

The following is a simple a Python function that takes a string as an incoming parameter and then prints it to the standard display device.

def printme (str):    " print an incoming string to a standard display device "   Print Str    return

2. Function calls

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 completed, you can execute it through another function call or directly from the The Python prompt executes.

Example 1:

#!/usr/bin/env python#-*-coding:utf-8-*-#@Time: 2016/9/22 22:29#@Author: Wwyxdefmy_print (str):"My first function"    Print "my fist:", strreturnMy_print ("666") My_print ("return to zero")

Example 1 run Result:

My fist:666my fist: zeroing

Passing parameters by value and passing parameters by reference

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

Example 2:

#!/usr/bin/env python#-*-coding:utf-8-*-#@Time: 2016/9/22 22:29#@Author: WwyxdefChange_var (mylist):"Changing list variables"Mylist.append ([1, 2, 3])    returnmylistmylist= [12, 23, 43]reslist=Change_var (mylist)Print "results After modifying a variable", reslist

Example 2 run Results

Results after modifying variables [12, 23, 43, [1, 2, 3]

3. Parameters

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

    • Required Parameters
    • Keyword parameters
    • Default parameters
    • Indefinite length parameter

3.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 My_print() function, you must pass in a parameter, or a syntax error will occur:

3.2 Keyword Parameters

Keyword arguments are closely related to function calls, and function calls use keyword parameters to determine the values of the parameters passed in.

The order of arguments is not consistent with the declaration when using the keyword argument to allow the function call, because the Python interpreter can match parameter values with the name of the argument.

Example 3:

#!/usr/bin/env python#-*-coding:utf-8-*-#@Time: 2016/9/22 22:29#@Author: WwyxdefPrintinfo (age, name):Print "Age :", AgePrint "Name:", Nameprintinfo (name="Demacia", age=" A")

Example 3 run Results

age:22Name: Demacia

3.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. The following example prints the default ageif age is not passed in:

Example 4

def printinfo (name,age=10):    print'age:',    age  print"name:", nameprintinfo (name="  Demacia ")

Example 4 run Result:

Age:10Name: Demacia

Note: The default parameter defaults must be the last parameter in the function parameter, that is, the default parameter must be followed by a non-default parameter.

3.4 Variable length Parameters

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]

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

Example 5

#!/usr/bin/env python#-*-coding:utf-8-*-#@Time: 2016/9/22 22:29#@Author: WwyxdefMany_arg (arg1, *many):Print "arg1:", Arg1 forVarinchMany:Print "Multiple Parameters", Varmany_arg (12, 12, 45, 78)

Example 5 Run Result:

arg1:1278

4. Anonymous functions

Python uses Lambda to create anonymous functions.

Lambda is just an expression, and the function body is much simpler than def.

the body of a lambda is an expression, not a block of code. Only a finite amount of logic can be encapsulated in a lambda 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.

Grammar

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

Lambda [Arg1 [, Arg2,..... argn]]:expression

Example 6:

# !/usr/bin/env python # -*-coding:utf-8-*- # @Time    : 2016/9/22 22:29#  @Author  : WwyxLambda add1, ADD2, ADD3:ADD1 + add 2 + add3print" addition and:", sums (10, 10, 10)

Example 6 Run Results

Addition and: 30

5.return Statements

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:

Example 7:

#!/usr/bin/env python#-*-coding:utf-8-*-#@Time: 2016/9/22 22:29#@Author: WwyxdefMyadd (Arg1, arg2): Toltal= Arg1 +arg2Print "addition and:", ToltalreturnToltalPrint "Call The addition method:", Myadd (10,23)

Example 7 Run Result:

Call addition Method: addition and: 3333

As you can see from the running result, the Python function call takes a recursive call.

6. Variable Scope

All variables of a program are not accessible in any location. Access permissions depend on where the variable is assigned.

The scope of the variable determines which part of the program you can access which particular variable name. The two most basic variables are scoped as follows:

    • Global variables
    • Local variables

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. When a function is called, all variable names declared within the function are added to the scope. The following example:

Example 8

#!/usr/bin/env python#-*-coding:utf-8-*-#@Time: 2016/9/22 22:29#@Author: WwyxTotal = 0#Global VariablesdefVar_scope (Arg1, arg2): Total= Arg1 + arg2#Local Variables    Print "Local Variables:", Totalreturn TotalPrint "Call function return variable", Var_scope (12, 32)Print "Global Variables", total

Example 8 Run Results

Call function return variable local variable: 4444 global variable 0

Python's Strongest King (9)--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.