Basic Python content: functions

Source: Internet
Author: User
Functions are organized and reusable, and used to implement a single, or associated function code segment. A function can improve the vigilance of an application and reuse the code. a self-created function is called a user-defined function. Function definition specification: 1. the Function Code block starts with the def keyword, followed by the function identifier name and parentheses (). 2. any input parameter and independent variable must be placed in the middle of the parentheses. the functions between the parentheses can be organized and reusable to implement a single or correlated function code segment. A function can improve the vigilance of an application and reuse the code. a self-created function is called a user-defined function. Function definition specification: 1. the Function Code block starts with the def keyword, followed by the function identifier name and parentheses ().
2. any input parameter and independent variable must be placed in the middle of the parentheses. the parentheses can be used to define parameters.
3. the first line of the function can selectively use the document string-used to store the function description.
4. the Function content starts with a colon and is indented.
5. return [expression] ends the function and selectively returns a value to the caller. Return without expression is equivalent to return None.
Function definition syntax: def function name (form parameter): By default, the parameter values and names are matched in the order defined in the function declaration. Example: # do not define the parameter >>> def
Show ():... print ('Show fun ')... >>> show () show fun simple area calculation function: >>> def
Area (height, width ):... a = height * width... return a...> area () 20 function call the function directly using the function name (). If the function name is used directly, the return address is the physical content of the function. when () is added, is the parameter parameters and real parameters that represent the execution of the function >>> def
Area (height, width ):... a = height * width... return a...> area () 20 in this example, the height and width parameters are used to define the structure and logic of the function, and the values 4 and 5 are real parameters, it is the actual input parameter when you call a function. the number of real parameters must be the same as that of the form parameter. during the call, the specific values of the form parameter correspond one to one according to the input sequence of the real parameter. for example, 4 corresponds to height, 5 corresponds to the width keyword parameter (specified parameter) use the keyword parameter to allow the order of parameters for function calling is inconsistent with the declaration, the specific usage is as follows>
Def area (height, width):... a = height * width... return a... >>>
Area (width = 5, height = 4) # When calling a function, specify the value of a specific parameter. If no parameter is passed when the default parameter is called, the default parameters are used. Default parameters must be defined at the end of all parameters>
Def stu (name, age, grade = 3):... print ('name is % s, age is % s, grade is % s' %
(Name, age, grade)... >>>
Stu ('Ian ', 10) # The grade parameter is not input here. by default, grade = is used.
3 name is
Ian, age is 10, grade is 3 >>>
Stu ('Isha', 9, 4) name is
Isha, age is 9, grade is 4 dynamic parameter # dynamic parameter 01, add all input real parameters to a ancestor def main2 (* arg): print (arg, type (arg) main2 (,) # dynamic parameter 02, add all input real parameters to a dictionary def main3 (** kwargs): print (kwargs, type (kwargs) main3 (k1 = 12, k2 = 'Ian ') # dynamic parameter 03, the above two items merge def
Main4 (* args, ** kwargs): print (args, type (args) print (kwargs, type (kwargs) main4 (1, 2, k1 = 12, k2 = 'Ian ') # The Order of the preceding parameters and the real parameters here cannot be reversed. Otherwise, an error is reported. # dynamic parameter 4. if the real parameter is a variable, how to specify to dynamic parameters ---> with * def
Main4 (* args, ** kwargs): print (args, type (args) print (kwargs, type (kwargs) m = [1, 2] n =
{'K1 ': 12, 'K2': 'Ian'} main4 (* m, ** n) Summary: Python functions have very flexible parameter forms, simple calls and complex parameters can be passed in. The default parameter must use an immutable object. if it is a mutable object, a logic error occurs during running! Note the syntax for defining variable parameters and keyword parameters: * args is a variable parameter, args receives a tuple, ** kwargs is a keyword parameter, and kwargs receives a dict. The use of * args and ** kwargs is a habit of writing in Python. of course, you can also use other parameter names, but it is best to use them in regular usage. Anonymous functions use lambda in python
To create an anonymous function. The so-called anonymity means that def is no longer used.
Define a function in such a standard form. 1. lambda is just an expression. the function is much simpler than def.
2. the body of lambda is an expression rather than a code block. Only limited logic can be encapsulated in lambda expressions.
3. lambda
A function has its own namespace and cannot access parameters outside its own parameter list or in a global namespace.
4. 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, thus increasing the running efficiency.
Anonymous function syntax lambda function syntax only contains one statement, as follows: lambda [arg1
[, Arg2,... argn]: expression example: >>>
Su = lambda a, B, c: a + B + c >>> su (, 3) 6 return statement return is used to exit the function, if you use the return [expression], an expression is returned when you exit the function. if you do not use the return parameter, none >>> def is returned.
Area (height, width):... a = height * width... return a...> ar =
Area (4, 5) >>>
Print ('area is ', ar) area is 20 global variables and local variables when you declare variables in the function definition, they have nothing to do with other variables with the same name outside the function, that is, the variable name is
Local. This is called the scope of a variable. The scope of all variables is the block they are defined, starting from the point where their names are defined. Local variable: def func (x): print ('X is ', x) x = 2 print ('changed local x to', x) x = 50 func (x) print ('X is still', x) returns: x is 50 Changed local x to 2x is still 50 using the global statement. if you want to assign a value to a variable defined outside the function, then you have to tell Python that the variable name is not local,
Global. We use the global statement to complete this function. Without a global statement, it is impossible to assign values to variables defined outside the function. Def func (): global x print ('X is ', x) x = 2 print ('changed local x to', x) x = 50 func () print ('X is still', x) returns: x is 50 Changed local x to 2x is still 2 # The global statement is used to declare that x is global. therefore, when we assign the value to x in the function, the value of x outside the function will also change directly.

The above is the basic content of Python: Function Details. For more information, see other related articles in the first PHP community!

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.