Python3 function (personal summary)

Summary: function is a good organization, reusable, code segments used to implement a single, or the associated function. Function module of the application can be improved, and code reuse.

First, the definition function

Syntax:

def 函数名(参数列表):
    函数体

Example:

>>> def pow(x):
		"返回传入数字的平方"
	    return x * x
>>> pow(3)
9

Second, the parameter type
parameter functions are required parameters, variable length parameters, keyword parameters, default parameters, see usage examples, details to view w3cschool

 def myprint(name, *hobby, **kw):
	print("name:{}".format(name))
	print("hobby:", end=" ")
	for i in hobby:
	    print(i, end=" ")
	if 'age' in kw:
	    print("age:{}".format(kw.get('age')))

	    
>>> myprint('lisi', 'book','music', age=18)
name:lisi
hobby: book music age:18
>>> myprint('lisi', 'book','music',sex='man')
name:lisi
hobby: book music 

Third, the higher order function
is defined: function parameter as a function of higher order functions for
several examples of higher-order functions built Python:

  • map function
    Function Description: map (func, Iterator):
    map function takes two parameters, the first parameter is a function func, the second parameter is a sequence. Each element of the sequence map function will have to call again the function func. And returns an iterator processed, can be converted to the function list by listing.

Examples

>>> def pow(x):
        return x * x
>>> re = list(map(pow, [1, 2, 3]))
>>> print(re)
[1, 4, 9]
  • reduce function
    Function Description: reduce (func, iterator):
    The first parameter is a function func, the function of two parameters, the second parameter is a sequence, each iteration will reduce function of a sequence of elements, the elements behind press process func function element, and returns the final result.

Example:

>>> def add(x, y):
        return x + y
>>> re = reduce(add, [1, 2, 3, 4])
>>> print(re)
10
  • The filter function
    Function Description: filter (func, iterator):
    parameters of filter function and sequence remains as a function, the function filtration functions, acting by the function func to each element, according to the result is True or False, the decision to retain or delete the element.
    And returns an iterator, similar to the map function.

Example:

>>> def even(x):
        try:
            if x % 2 == 0:
                return True
        except Exception:
            return False
        return False
>>> re = list(filter(even, [1, 2, 3, 4]))
>>> print(re)
[2, 4]
Published 40 original articles · won praise 31 · views 620 000 +

Guess you like

Origin blog.csdn.net/weixin_38422258/article/details/104355751