1.局部变量和全局变量
x = 0
def grandpa():
x = 1
def dad():
x = 2
def son():
x = 3
print(x)
son()
dad()
grandpa()
print(x)
结果:
3
0
2.递归函数
##递归实现阶乘的
def func(n):
if n==1:
return 1
else:
return n*func(n-1)
print(func(4))
#24
3.高阶函数
满足下列条件之一就可称函数为高阶函数
-
某一函数当做参数传入另一个函数中
-
函数的返回值包含一个或多个函数
-
#简单的高阶函数 def func(): print('in the func') return foo() def foo(): print('in the foo()') return 666 res = func() print(res) 结果: in the func in the foo() 666
4.匿名函数
-
lambda 函数是一种快速定义单行的最小函数,可以用在任何需要函数的地方
优点:让代码更加精简,不需要考虑命名的问题
-
#简单的匿名函数 lambda x,y:x+y #等价于 def (x,y): return x+y
5.函数式编程
- 编程主流的形式分为面向过程、面向对象、函数式编程
- 函数式编程就是一种抽象程度很高的编程范式,纯粹的函数式编程语言编写的函数没有变量,因此,任意一个函数,只要输入是确定的,输出就是确定的,这种纯函数我们称之为没有副作用。而允许使用变量的程序设计语言,由于函数内部的变量状态不确定,同样的输入,可能得到不同的输出,因此,这种函数是有副作用的。
6.filter 函数、reduce函数、map函数
map()是 Python 内置的高阶函数,它接收一个函数 f 和一个list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回
reduce()函数也是Python内置的一个高阶函数。reduce()函数接收的参数和 map()类似,一个函数 f,一个list,但行为和 map()不同,reduce()传入的函数 f 必须接收两个参数,reduce()对list的每个元素反复调用函数f,并返回最终结果值
filter()函数是 Python 内置的另一个有用的高阶函数,filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list
res=filter(lambda x:x.endswith('sb'),['ni_sb','hua_sb','liu '])
res=map(lambda x:x+2,[1,2,3])
res=reduce(lambda x,y:x+y,[1,2,3])
print(res)
#自己实现filter,map,reduce
def filter_test(func,array):
ret=[]
for p in array:
if not func(p):
ret.append(p)
return ret
def map_test(func,array): #func=lambda x:x+1 arrary=[1,2,10,5,3,7]
ret=[]
for i in array:
res=func(i) #add_one(i)
ret.append(res)
return ret
def reduce_test(func,array,init=None):
if init is None:
res=array.pop(0)
else:
res=init
for num in array:
res=func(res,num)
return res
7.max、min、sort函数
people=[
{'name':'alex','age':1000},
{'name':'wupei','age':10000},
{'name':'yuanhao','age':9000},
{'name':'linhaifeng','age':18},
]
###找出年纪最大的人
res=max(people,key=lambda i:i['age'])
print(res)
###找出年纪最小的人
res=min(people,key=lambda i:i['age'])
print(res)
###按年纪排序
res=sorted(people,key=lambda i:i['age'])
print(res)