First, the function
If a program, some of the code I need to repeat the use of, for example, every piece of code prints five times "you are good"
1. Overview of functions
1.1 awareness function
Function : In a complete project, certain functions will be repeated use, it will feature repeated use, it will function as a function of the package, when we want to use this feature calls can be.
advantage:
1. Simplified code structure, increasing the reusability of code (the degree of repeated use)
2. Increase the maintainability of the code, if you want to modify a BUG, only the corresponding function can be.
1.2 Definitions Function
format:
def function (parameter list):
Statement
return expression
Explanation:
def : def function block to start with keywords
Function name : follow the rules for identifiers
Parameter List : Any parameters and variables passed into the function, must be placed between parentheses, separated by commas function to obtain information from the caller of the function where [the caller] passed to the function information
() : The beginning and end of the argument list
Colon : function contents [] function package begins with a colon, and the indentation
Statement : function package features
return : generally used for the end of the function, and return information to the caller of the function
Expression : To return to the caller's information function
Note : The final return expression can not write, if the default return None case of written
= Parameter list parameter 1, parameter 2, ..., parameter n
1.3 function calls
Syntax: function name (parameter list)
Function name: function name of the function is to be used functions
Parameter List: Information caller of the function passed to the function
The nature of the function call: the argument to a procedure parameter assignment
>>> int(1.3)
1
>>> abs(-10)
10
1.4 The most simple function
Description: The most simple function, no parameters, no return value of the function
#定义函数
def myPrint():
print("you are a good man")
#调用函数
myPrint()
1.5 Function parameters
Parameter List: If demand functions relate to the realization of the unknowns involved in computing, the unknowns can be set as a parameter.
Format: parameter 1, parameter 2, parameter 3, ...
Formal parameters: as defined in the method, for receiving the value of the time parameter
Actual parameters: function definition on the outside, the actual values involved in operation, is to assign to the formal parameters
#函数的定义
#name是形参
def myPrint(name):
print("%s is a good man !"%name)
#"lili" 是实参
myPrint("lili")
#结果
lili is a good man !
#形参 参数一:name 参数二:age
def myPrint(name, age):
print("%s is %d year old"%(name, age))
#函数调用,传递两个参数
myPrint("lili", 18)
#结果
lili is 18 year old
1.6 the return value of the function
Return value of a function represented by a function of the results obtained after the completion of execution
Use the return value of the function Return, for ending the function, to obtain a final operation result.
Demand: Write a function to achieve the function, you pass two integers to obtain the sum of two integers
def add(num1, num2):
sum = num1 + num2
#将结果返回函数的调用者
return sum
#注意:return的作用是结束整个函数,因此return后面的语句不会被执行
print("hello")
#调用函数
res = add(10, 20)
print(res)
1.7 parameter passing
Parameters passed nature: argument to a procedure parameter assignment
Values of positional parameters passed 1.7.1
Transfer means transfer the value of immutable type, generally refers string, tuple type and number
def func1(a):
print(a)
a = 10
print(a)
temp = 20
#将temp作为实参传递给func1函数,将赋值给形参a
#相当于 a = temp
func1(temp)
print(temp)
Print the address below
def func1(a):
print(id(a))
a = 10
print(id(a))
temp = 20
#将temp作为实参传递给func1函数,将赋值给形参a
#相当于 a = temp
print(id(temp))
func1(temp)
print(temp)
1.7.2 positional parameters of reference passed
Reference variable transmission is generally transmitted type, generally refers to the list, dict and set
def func1(c):
c[0] = 100
d =[1, 2, 3, 4]
#将引用传递过去
func2(d)
print(d[0])
Explanation: The value is passed or essentially passed by reference, but the pass is the address
Also known as the location parameter a mandatory parameter
1.7.3 keyword arguments
Concept: When a function is called, through - to be specified in the form "key value", the function can make more clear, easy to use, but also cleared the parameters of the order needs
def func(name, age):
print("I am %s, and I am %d year old"%(name, age))
#一般调用
func("lili", 18)
#使用关键字参数
func(age = 18, name = "lili")
Note: When there are position parameters, location parameters must be in front of the keyword arguments, but does not exist between key parameters of the order.
1.7.4 default parameters
Concept: which defines its function, to provide default values for the parameters, may be passed by value of the function is called default parameters.
When you call the function, the default parameters if no parameter will be used
For example: when using sort () sort of, do not change the default parameters when we normally would in ascending order
def func(name, age=18)
print("I am %s, and I am %d year old"%(name, age))
#一般的函数调用
func('lilei', 19)
#关键字参数调用
func(name = 'leilei')
#使用默认参数调用
func('lili')
Use the default parameters can simplify the calling function.
When using the default parameters must be noted:
1. The first mandatory parameter, after the default parameters, or error python interpreter
2. The default parameter must point to the same objects
How to set the default parameters
When the function has a plurality of parameters, the large parameter changes on the front, small changes on the back, a small change can be used as default parameters.
Exercise:
We wrote a primary school enrollment information, ask for information as name, gender, age, city, etc., a design function.
def student(name, sex, age = 6, city = '广州'):
print("name :", name)
print("sex :",sex)
print("age :",age)
print("city :",city)
#函数调用
student('lili', 'boy')
student('lili', 'boy', 7)
student('lili', 'boy', city='Beijing')
Note: When there are multiple default parameters, can provide default parameters in order, when the order does not provide the parameters that need to be called using keyword arguments.
1.7.5 variable length parameters [variable Parameters
The concept: When you define a function, sometimes when we are not sure how many calls are passed parameter (or number of passing parameters to 0), then we can use the parcel or parcels position parameter keyword arguments to pass parameters.
Features: can handle more parameters than the original statement, in other words, the number of parameters passed, I will deal with the number of parameters, do not pass is not processed
Parcel delivery location - * args
#与之前形参不同的是在hoby的变量名之前添加了“*”
#添加了星号(*)的变量名会存放所有未命名的变量参数
#如果在函数调用时没有指定参数,它就是一个空的元组
#一般情况下使用*args
def func(name, *hoby):
print("I am ",name,"I like",hoby)
func('lili','flower','money')
Note: All parameters we pass in will be collected args variable, depending on the position he will be merged into pass into the parameters of a tuple (tupe), args is a tuple type, this is the location of the parcel delivery.
2. Keyword parcel delivery - ** kwargs
#若是两个*,则当做dict处理
# 注意:在使用**kwargs的时候,传递参数必须使用关键字传参
def func(**kwargs):
print(kwargs)
print(type(kwargs))
func(x = 1, y = 2)
#能处理任意长度的参数
def func(*args, **kwargs):
#代表一个空语句
pass
kwargs is a dictionary (dict), collect all the keyword arguments.
Note: Defined Functions in python, you can use mandatory parameters, default parameters, variable parameters and keyword parameters, these four parameters can be used together or only some of them, but note that the parameters are defined and called order must be: a required parameter [position] parameter, the default parameters, variable parameter [position] parcel wrapped keywords and keyword parameters [] .
1.7.6 Anonymous functions
Concept: No definition refers to a class identifier (function name) function or subroutine.
Features: Anonymous function does not use def-defined functions, using lambda to create an anonymous function
1.lambda just an expression, is simpler than the function body def
2. Keyword lambda represents an anonymous function, before the colon x denotes a function parameter.
3. anonymous function has a limit, that is only one expression, do not write return, the return value is the result of the expression.
grammar:
lambda parameter 1, parameter 2, ..., parameter n: expression [Expression]
Benefits : function has no name, do not worry about the function name conflict, in addition, an anonymous function is a function object can also assign an anonymous function to a variable, and then use a variable to call the function.
sum = lambda num1, num2: num1 + num2
print(sum(1, 2))