Python函数的目的是降低编程难度、增加代码复用。
介绍
格式定义:
def 函数名(参数1, 参数2):
    实现语句
    实现语句
    return ...
def 函数名(positional_only_parameters, /, positional_or_keyword_parameters,*, keyword_only_parameters):
说明:
- 函数名其实就是一个函数对象的引用,可以赋值给其他变量,等于起个别名
- 
参数:
- 仅位置参数(positional-only)在- /之前定义的参数,传参时不带变量名- 
- python3.8 引入了仅位置参数,内置函数早已使用该方法,可参考 help(sum)
 
- 位置或关键字参数(positional_or_keyword)- 
- 在 /后面和*号前面定义的参数,这里是我们自定义函数时最常用的
- 传参时可以把它当作位置参数或关键字参数看待,可以带变量名也可以不带
 
- 集合位置参数(var_positional)函数定义时采用- *args定义,是- 可变参数,args 接收的是一个 tuple
- 仅关键字参数(keyword-only)在- *后面定义的参数(或在- *args后面定义),传参时必需带变量名
- 集合关键字参数(var_keyword)函数定义时采用- **kargs指定的参数,- **kwargs接收的是一个 dict,传参时必须带变量名
 
- 返回值
- 函数没有 return时,自动return None。return None可以简写成return
- 返回多个值其实就是返回了一个 tuple
 
内建函数
- len函数返回序列中所包含元素的数量
- min和- max函数返回序列中的最小值和最大值
- python内建了 map(),reduce(),filter()函数。这些函数接受两个参数,一个是函数,一个是序列。
map(lambda x: x ** 2, [1, 2, 3, 4, 5])
返回结果为:
[1, 4, 9, 16, 25]
- reduce函数会对参数序列中元素进行累积,py3以后使用,必须导入- from functools import reduce
def myadd(x,y):
    return x+y
sum=reduce(myadd,(1,2,3,4,5,6,7))
print(sum) # 结果就是输出1+2+3+4+5+6+7的结果即28
def is_even(x):
    return x & 1 != 0
filter(is_even, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
# 返回结果为:
[1, 3, 5, 7, 9]
- Python 内置的 sorted(iterable, key=None, reverse=False)可以对list进行排序
a_list = ["aaa", "cc", "bb"]
# Sort by length then alphabetically
new_list = sorted(a_list, key=lambda x: (len(x), x))
print(new_list)
# ['bb', 'cc', 'aaa']
- map(func, *iterables)Make an iterator that computes the function using arguments from each of the iterables.
>> [i for i in map(lambda x: x*2, range(1, 10))]
[2, 4, 6, 8, 10, 12, 14, 16, 18]
内名函数
lambda关键字表示匿名函数,例如:
f = lambda x: x * x
匿名函数有个限制:只能有一个表达式,不用写return,返回值就是结果。
函数 vs generator
- Generator是边用边生成,而不是一次性生成。下面示例中,a就是一个 generator,和- [x * x for x in range(5)]不同:
a = (x * x for x in range(5))