Python Learning Note: Seventh Day (function)

Source: Internet
Author: User
Tags variable scope

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

Like C, Python provides a number of built-in functions, such as print (). You can also create your own functions, which are called user-defined functions.

1. 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, 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.
<1> Grammar

The Python definition function uses the DEF keyword, and the general format is as follows:

def function name (argument list):    function body

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

<2> examples
#!/usr/bin/python3# Calculate area Function def areas (width, height):    return width * height def print_welcome (name):    Print (" Welcome ", name) print_welcome (" Yu ") w = 4h = 5print (" width = ", W," height = ", h," area = ", Area (W, h))

2. Function call

Define a function: Give the function a name, specify the parameters contained in the function, and the code block structure.

Once the basic structure of this function is complete, it can be executed through another function call or directly from the Python command prompt.

The following instance calls the printme () function:

#!/usr/bin/python3 # defines the function Def printme (str):   "Prints any incoming string" Print   (str);   Return # Call Function Printme ("I want to invoke user-defined function!"); Printme ("Call the same function again");

3. Parameter passing

In Python, a type belongs to an object, and a variable is of no type.

<1>can Change (mutable) and non-changing (immutable) objects

In Python, strings, tuples, and numbers are objects that cannot be changed, and List,dict are objects that can be modified.

    • immutable Type: variable assignment a=5 and then assign value a=10, here is actually reborn into an int value object 10, then a point to it, and 5 is discarded, not change the value of a, the equivalent of a new student into a.

    • Variable type: variable assignment la=[1,2,3,4] after assigning a value la[2]=5 is to change the value of the third element of List LA, itself LA is not moving, but its internal part of the value has been modified.

Parameter passing of the Python function:

    • immutable types: values such as C + + are passed, such as integers, strings, and tuples. such as fun (a), passing only a value, does not affect the A object itself. For example, in Fun (a) to modify the value of a, just modify another copy of the object, does not affect the a itself.

    • mutable types: references such as C + + are passed, such as lists, dictionaries. such as Fun (LA), is the real transfer of LA, the modified fun outside of LA will also be affected

Everything in Python is an object, strictly meaning we can't say value passing or reference passing, we should say immutable objects and pass mutable objects.

4. 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
<1> Required Parameters

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

#!/usr/bin/python3 #可写函数说明def printme (str):   "Prints any incoming string" Print   (str);   Return #调用printme函数printme ();

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

  TypeError : printme() missing 1 required positional argument: ' str '

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

Using the keyword argument allows a function call when the order of the arguments is inconsistent with the Declaration, because the Python interpreter can match the parameter values with the name of the argument.

The following example shows that the use of function parameters does not need to use the specified order:

#!/usr/bin/python3 #可写函数说明def Printinfo (name, age):   "Print any incoming string" Print   ("Name:", name);   Print ("Age:", ages);   Return #调用printinfo函数printinfo (age=50, name= "Yu");
<3> Default Parameters

When a function is called, default parameters are used if no arguments are passed. The default value is used if the age parameter is not passed in the following instance:

#!/usr/bin/python3 #可写函数说明def Printinfo (name, age = +):   "Print any incoming string" Print   ("Name:", name);   Print ("Age:", ages);   Return #调用printinfo函数printinfo (age=50, name= "Yu");p rint ("------------------------") printinfo (name= "Yu");
<4> Indefinite length parameters

A function 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. If a parameter is not specified when the function is called, it is an empty tuple. We can also not pass unnamed variables to the function. The following example:

#!/usr/bin/python3 # writable function Description def printinfo (arg1, *vartuple):   "Print any incoming parameters" print   ("Output:")   print (arg1)   For Var in vartuple:      print (VAR)   return; # call printinfo function Printinfo (70, 60, 50);p Rintinfo;

5. Anonymous function

Python uses lambda to create anonymous functions.

Anonymity means that a function is no longer defined in a standard form such as a DEF statement.

    • 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.
<1> Grammar

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

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

The following example:

#!/usr/bin/python3 # writable function Description sum = lambda arg1, arg2:arg1 + arg2; # Call the SUM function print ("the added value is:", sum (Ten)) print ("The added value is:", SUM (20, 20))

6. Return statement

The return [expression] statement is used to exit 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 demonstrates the use of the return statement:

#!/usr/bin/python3# writable function Description def sum (arg1, arg2):   # Returns the sum of 2 parameters. "   Total = arg1 + arg2   print ("Inside function:")   return total;# call the sum function total = SUM (Ten);p rint ("Out of function:", sum)
7. Variable Scope

In Python, a program's variables are not accessible in any location, and access is determined by where the variable is assigned.

The scope of a variable determines which part of the program can access which particular variable name. There are 4 types of Python scopes, namely:

    • L (local) local scope
    • In functions outside of the E (enclosing) closure function
    • G (Global) scope
    • B (built-in) built-in scopes

To l–> e–> g–>b rules to find, that is: in the local can not find, will go to local outside the local search (such as closures), and can not find the overall look, and then to the built-in search.

Only modules, classes, and functions (Def, Lambda) in Python introduce new scopes, and other blocks of code (such as if/elif/else/, Try/except, For/while, and so on) do not introduce new scopes. That is, the variables defined within these statements can also be accessed externally.

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

<2> Global and Nonlocal keywords

The Global and nonlocal keywords are used when the internal scope wants to modify the variables of the outer scope.

The following instance modifies the global variable num:

#!/usr/bin/python3num = 1def fun1 ():    global num  # requires the use of the global keyword to declare    print (num)     num = 123    print (num) FUN1 ()

If you want to modify a variable in a nested scope (enclosing scope, outer non-global scope) You need to nonlocal the keyword, as in the following example:

#!/usr/bin/python3 def outer ():    num = ten    def inner ():        nonlocal num   # nonlocal keyword declaration        num =        Print (num)    inner ()    print (num) outer ()

Python Learning Note: Seventh Day (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.