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

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.
Instance
Let's use the function to output "Hello world! ":

>>> def hello ():   print ("Hello world!")   

For more complex applications, the function takes a parameter variable:

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

The result of the above example output:

Welcome runoobwidth = 4  height = 5 area  = 20

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, you can execute it 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");

The result of the above example output:

I want to invoke the user custom Function! Call the same function again

Parameter passing
In Python, a type belongs to an object, and a variable is of no type:

A=[1,2,3]a= "QQ603374730"

In the above code, [All-in-one] is a list type, "Runoob" is a string type, and variable A is no type, she is simply a reference to an object (a pointer), either a list type object, or a string type object.

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.

Python-Pass Immutable object instance

#!/usr/bin/python3 def Changeint (a):    a = 10b = 2ChangeInt (b) print (b) # The result is 2.

The instance has int object 2, the variable that points to it is B, and when passed to the Changeint function, the variable b,a and B both point to the same int object, and at a=10, the new int value Object 10, and a points to it.

Passing a Mutable object instance
A mutable object modifies a parameter in a function, and the original parameter is changed in the function that calls the function. For example:

#!/usr/bin/python3 # writable function Description def changeme (mylist):   "Modify incoming list"   mylist.append ([1,2,3,4]);   Print ("Value within function:", mylist)   return # call changeme function mylist = [10,20,30];changeme (mylist);p rint ("Out-of-function value:", MyList)

The same reference is used for an object that passes in the function and adds new content at the end. So the output is as follows:

Values in function:  [10, 20, 30, [1, 2, 3, 4]] values outside the function:  [10, 20, 30, [1, 2, 3, 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

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

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

The result of the above example output:

Traceback (most recent):  File "test.py", line ten, in <module>    printme (); Typeerror:printme () Missing 1 required positional argument: ' str '

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 instance uses the parameter name when the function Printme () is called:

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

The result of the above example output:

QQ9603374730

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= "QQ603374730");

The result of the above example output:

Name:  QQ603374730 Age:  50

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= "QQ603374730");p rint ("------------------------") Printinfo (name= " QQ603374730 ");

The result of the above example output:

Name:  QQ603374730 Age:  ------------------------Name:  QQ603374730 Age:  35

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]

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;

The result of the above example output:

Output: 10 Output: 706050

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

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

The result of the above example output:

The added value is:  30 The added value is:  40

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)

The result of the above example output:

Function:  30 outside of function:  30

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 scopes in Python, 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.

x = Int (2.9)  # built-in scope g_count = 0  # global Scope def outer ():    o_count = 1  # function outside the closure function    def inner ():        i_count = 2  # local scope

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. In other words, the variables defined inside these statements can be accessed externally as well, as in the following code:

>>> If True: ...  

The MSG variable in the instance is defined in the IF statement block, but is externally accessible.
If the MSG is defined in a function, it is a local variable that cannot be accessed externally:

>>> def test (): ...     Msg_inner = ' I am from Runoob ' ... >>> msg_innertraceback (most recent call last):  

From the information on the error, it shows that msg_inner is undefined and cannot be used because it is a local variable and can only be used within a function.

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:

#!/usr/bin/python3total = 0; # This is a global variable # writable function description def sum (arg1, arg2):    #返回2个参数的和. "    Total = Arg1 + arg2; # Total is a local variable here.    Print ("Inside the function is a local variable:", total)    return full; #调用sum函数sum (+);p rint ("Outside the function is a global variable:", total)

The result of the above example output:

Inside a function is a local variable:  30 is a global variable outside the function:  0

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 ()

The result of the above example output:

1123

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 ()

The result of the above example output:

100100

There is also a special case where the following code is assumed to be running:

#!/usr/bin/python3 a = 10def test ():    a = a + 1    print (a) test ()

The above procedure executes, the error message is as follows:

Traceback (most recent):  file "test.py", line 7, <module>    Test ()  file "test.py", line 5, in Test    A = a + 1unboundlocalerror:local variable ' A ' referenced before assignment

The error message is a local scope reference error because a in the test function uses a local, undefined, and cannot be modified.

python015 Python3 function

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.