Python Basics-Functions

Source: Internet
Author: User
Tags closure

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


second, the grammar
the Python definition function uses the DEF keyword, and the general format is as follows:
def function name (parameter list):
function Body
By default, parameter values and parameter names are matched in the order defined in the function declaration.


third, parameter transfer
1. In Python, a type belongs to an object, and the variable is of no type.
a=[1,2,3]
A= "Hello"
In the above code, [All-in-one] is a list type, "Hello" is a string type, and variable A is no type, she is simply a reference to an object (a pointer), either to a list type object or to a string type object.

2. Can change (mutable) and non-change (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.

3, the parameters of the Python function pass:
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


4. Examples of Python-passed immutable objects

#!/usr/bin/python3def Changeint (a):         22   int2, 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, in a=int and let a point to it. 


5. Python Transfer Variable object instance

#!/usr/bin/Python3 # Writable function Description def changeme (mylist):"to modify an incoming list"Mylist.append ([1,2,3,4]) print ("value in function:", MyList)return# Call the Changeme function MyList= [Ten, -, -]changeme (mylist) print ("values outside the function:", mylist) function values: [Ten, -, -, [1,2,3,4] ] Outside the function: [Ten, -, -, [1,2,3,4] ] The same reference is used for an object that passes in the function and adds new content at the end.  


Iv. parameters
The following are the formal parameter types that can be used when calling a function:
1. Required Parameters
2. Keyword parameters
3. Default parameters
4. 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.


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.

3. Default parameters
When a function is called, default parameters are used if no arguments are passed.

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


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.

Grammar
The syntax for a lambda function contains only one statement, as follows:
Lambda [arg1 [, Arg2,..... argn]]:expression



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



Vi. Scope of variables
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.
Cases:

int (2.9)   0   # Global Scope def outer (    ):1  # in functions outside the closure function    def inner ():        2  # Local Scope



Python Basics-Functions

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.