Python's strongest King (9)-functions, python's highest

Source: Internet
Author: User
Tags variable scope

Python's strongest King (9)-functions, python's highest

1. Python Functions

Functions are organized and reusable, and used to implement a single, or associated function code segment.

Functions can improve the app's vigilance and reuse of code. You already know that Python provides many built-in functions, such as print (). But you can also create a function by yourself, which is called a user-defined function.

Define a function

You can define a function that you want to function. The following are simple rules:

The function code block starts with the def keyword, followed by the Function Identifier name and parentheses ().

Any input parameters and independent variables must be placed in the middle of parentheses. Parentheses can be used to define parameters.

The first line of a function can selectively use the document string-used to store the function description.

The function content starts with a colon and is indented.

Return [expression] ends the function and returns a value to the caller selectively. Return without expression is equivalent to return None.

Syntax

Def functionname (parameters): "function _ document string" function_suite return [expression]

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

Instance

The following is a simple Python function that uses a string as an input parameter and prints it to a standard display device.

Def printme (str): "print the input string to the Standard Display Device" print str return

2. function call

Defining a function only gives the function a name, specifying the parameters contained in the function and the code block structure.

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

Example 1:

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/22 # @ Author: wwyxdef my_print (str ): "my first function" print "my fist:", str returnmy_print ("666") my_print ("zeroes ")

Example 1 running result:

My fist: 666my fist: return to zero

Passing parameters by value and passing parameters by reference

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

Example 2:

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/22 # @ Author: wwyxdef change_var (mylist): "Change List variable" mylist. append ([1, 2, 3]) return mylistmylist = [12, 23, 43] reslist = change_var (mylist) print "result after variable modification", reslist

Example 2 running result

Result of variable modification [12, 23, 43, [1, 2, 3]

3. Parameters

The following are the formal parameter types that can be used to call a function:

  • Required Parameter
  • Keyword Parameter
  • Default parameters
  • Variable Length Parameter

3.1 required parameters

Required parameters must be input to the function in the correct order. The number of calls must be the same as that of the clear call.

To call the my_print () function, you must input a parameter. Otherwise, a syntax error occurs:

3.2 keyword Parameters

Keyword parameters are closely related to function calls. function calls use keyword parameters to determine input parameter values.

When you use keyword parameters to allow function calls, the order of parameters is inconsistent with that during declaration, because the Python interpreter can use the parameter name to match the parameter value.

Example 3:

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/22 # @ Author: wwyxdef printInfo (age, name): print "age: ", age print" name: ", nameprintInfo (name =" demassiya ", age =" 22 ")

Example 3 running result

Age: 22 name: demasia

3.3 default parameters

When a function is called, if the default parameter value is not passed in, it is considered as the default value. The default age is printed at the next meeting. If the age is not passed in:

Example 4

Def printInfo (name, age = 10): print "age:", age print "name:", nameprintInfo (name = "demasia ")

Example 4 running result:

Age: 10 name: demasia

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

3.4 indefinite Parameters

You may need a function to process more parameters than when it was originally declared. These parameters are called indefinite parameters. Unlike the preceding two parameters, they are not declared. The basic syntax is as follows:

Def functionname ([formal_args,] * var_args_tuple): "function _ document string" function_suite return [expression]

Variable names with asterisks (*) are used to store all unnamed variable parameters. You can also choose not to pass parameters. Example:

Example 5

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: # @ Author: wwyxdef many_arg (arg1, * Records): print "arg1: ", arg1 for var in parameters: print" multiple parameters ", varmany_arg (12, 12, 45, 78)

Example 5 running result:

Arg1: 12 multiple parameters 12 multiple parameters 45 multiple parameters 78

4. Anonymous Functions

Python uses lambda to create anonymous functions.

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

The body of lambda is an expression rather than a code block. Only limited logic can be encapsulated in lambda expressions.

Lambda functions have their own namespaces and cannot access parameters outside their own parameter lists or in global namespaces.

Although lambda functions seem to be able to write only one row, they are not equivalent to C or C ++ inline functions. The latter aims to call small functions without occupying the stack memory to increase the running efficiency.

Syntax

The syntax of the lambda function only contains one statement, as follows:

lambda [arg1 [,arg2,.....argn]]:expression

Example 6:

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/22 # @ Author: wwyxsums = lambda add1, add2, add3: add1 + add2 + add3print "addition and:", sums (10, 10, 10)

Example 6 running result

Addition and: 30

5. return Statement

Return Statement [expression] exits the function and selectively returns an expression to the caller. The return statement without the Parameter Value Returns None. The previous examples do not demonstrate how to return a value. The following example shows how to do this:

Example 7:

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/22 # @ Author: wwyxdef myadd (arg1, arg2 ): toltal = arg1 + arg2 print "addition and:", toltal return toltalprint "Call addition method:", myadd)

Example 7 running result:

Call the addition method: Addition and: 3333

From the running results, we can see that python function calls adopt recursive calls.

6. variable scope

All variables of a program are not accessible anywhere. The access permission determines where the variable is assigned.

The scope of a variable determines which specific variable name you can access in the program. The scopes of the two most basic variables are as follows:

  • Global Variables
  • Local variable

Global and local variables

Variables defined in a function have a local scope and global scopes defined outside the function.

Local variables can only be accessed within the declared function, while global variables can be accessed within the entire program. When a function is called, all variable names declared in the function will be added to the scope. Example:

Example 8

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/22 # @ Author: wwyxtotal = 0 # global variable def var_scope (arg1, arg2): total = arg1 + arg2 # local variable print "local variable:", total return totalprint "call function return variable", var_scope (12, 32) print "global variable", total

Example 8 running result

Call the function to return a local variable: 4444 global variable 0

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.