Python [4]-functions, python Functions
I. define functions
Define a function to use
def
Statement, write the function name, parameters in parentheses, and colons in sequence:
Then, write the function body in the indent block. The return value of the function isreturn
Statement. If noreturn
Statement. After the function is executed, the result is returned, but the result isNone
..
def add(a,b): return a+bprint add(1,2)
Pass can be used to define empty Functions
def nop(): pass
When defining a function, you must determine the function name and number of parameters;
If necessary, check the data type of the parameter. You can use built-in functions to check the data type.isinstance
Implementation.
Ii. function return values
The function body can be used internally.return
Returns function results at any time;
No function execution completedreturn
Statement, automaticallyreturn None
.
A function can return multiple values at the same time, which is essentially a tuple.
def test(a,b,rank): c=a+rank d=b+rank return c,dc,d=test(2,3,5)print cprint dt=test(5,10,1)print t
Iii. Function Parameters
① Default parameters
def power(x,n=2): r=1 while(n>0): r=r*x n=n-1 return rprint power(2)>>4print power(2,10)>>1024
Note the following when setting default parameters:
First, the required parameter is in the front, and the default parameter is in the back;
Second, default parameters must point to unchanged objects.
② Variable parameters
Variable parameters allow you to input 0 or any parameter. These variable parameters are automatically assembled into a tuple during function calling. When defining variable parameters, add a star number * Before the variable name *.
def sum(*numbers): s=0 for x in numbers: s=s+x*x return sprint sum(1,2,3,4,5)>>>55
If the parameter is list or turple, you must add a star number before the variable name.
list=[1,2,3,4,5]print sum(*list)>>>55t=(1,2,3,4,5)print sum(*t)>>>55
③ Keyword Parameters
Keyword parameters allow you to input 0 or any parameters with parameter names. These keyword parameters are automatically assembled into a dict in the function.
def show(name,age,**param): print "name",name,"age",age,paramshow('liu',20,city='beijing',job='teacher')dic={'city':'beijing','job':'teacher','home':'hubei'}show('zhang',30,**dic)
Note that the order of parameter definitions must be: mandatory parameters, default parameters, variable parameters, and keyword parameters.
④ Summary
The default parameter must use an immutable object. If it is a mutable object, a logic error occurs during running!
Pay attention to the syntax for defining variable parameters and keyword parameters:
*args
Is a variable parameter, and args receives a tuple;
**kw
Is a keyword parameter, and kw receives a dict.
How to pass in the syntax of variable and keyword parameters when calling a function:
Variable parameters can be passed in directly:func(1, 2, 3)
, You can first assemble list or tuple, and then pass*args
Input:func(*(1, 2, 3))
;
Keyword parameters can be passed in directly:func(a=1, b=2)
Dict can be assembled first, and then**kw
Input:func(**{'a': 1, 'b': 2})
.
Iv. Anonymous Functions
In python, the lambda keyword is used to define anonymous functions.
For example, sort the elements of a string set by length.
S = ['hello', 'World', 'a'] s. sort (key = lambda x: len (x) print s running result: ['A', 'Hello', 'World']
V. Function kerialization
Function colialization is to fix several parameters of a function, so as to generalize multiple functions of different meanings. This requires the built-in partial function of the functools module. For example:
From functools import partialdef addNumber (a, B): return a + baddNumber10 = partial (addNumber, 10) addNumber20 = partial (addNumber, 20) print addNumber10 (100) # Running result 110 print addNumber20 (100) # running result 120