01Python Basic _ 07 function, 01python_07 Function
1. define functions
1 def add(x, y):2 """Add two numbers.
The two values must be integers or strings""" #DocStrings3 a = x + y4 return a
DocStrings: the string of the first logical line of the function is the function'sDocument string. Note that DocStrings also applies to modules and classes. A document string is a multi-line string whose first line starts with an uppercase letter and ends with a full stop. The second line is empty, and the detailed description starts from the third line.
Return returns a specific value. If omitted, returnNone
.
2. Set default parameters
When defining a function, you can set the default value of the parameter:
Def quad (x, a = 1, B = 0, c = 0): return a * x ** 2 + B * x + cprint quad (2.0) # omit parameters with default parameters and assign only values to x
Out: 4.0
Print quad (2.0, B = 3) # assign values to parameters with default parameters
Out: 10
3. Accept indefinite Parameters
Def add (x, * args): # The parameter after x is treated as the element total = x for arg in args: total + = arg return totalprint add (1, 2, 3, 4) # it can be understood as: 1, (2, 3, 4) print add (1, 2)
Out: 10
3
You can also use keywords to input parameters:
Def add (x, ** kwargs): # ** kwargs is equivalent to a dictionary of total = x for arg, value in kwargs. items (): print "adding", arg total + = value return totalprint add (10, y = 11, z = 12, w = 13) # it can be understood as: 10, {y: 11, z: 12, w: 13}
Out: adding y
Adding z
Adding w
46
4. Input tuples and dictionaries
Def add (x, y): "" Add two numbers "a = x + y return a z = (2, 3) print add (* z) # "*" required w = {'X': 2, 'y': 3} print add (** w) # "**" Required
5. map Method generation Sequence
You can usemap
Using functions to generate sequences:
def sqr(x): return x ** 2a = [2,3,4]print map(sqr, a)
Out: [4, 9, 16]
Based on the number of function parameters,map
Multiple groups of sequences are acceptable:
def add(x, y): return x + ya = (2,3,4)b = [10,5,3]print map(add,a,b)
Out: [12, 8, 7]