1. 函数中的局部变量和全局变量
>>> count = 3
>>> def MyFun():
global count
count = 10
print(count)
>>> MyFun()
10
>>> print(count)
10
2. 内嵌函数
>>> def fun1():
print('fun1()正在被调用...')
def fun2():
print('fun2()正在被调用...')
fun2()
>>> fun1()
fun1()正在被调用...
fun2()正在被调用...
3. >>> def Fun1(x):
def Fun2(y):
return x*y
return Fun2
>>>
>>> i = Fun(8)
>>> i(5)
40
>>> Fun1(5)(8)
40
4. 函数中的局部变量和全局变量
例1: 列表在函数中局部和全局变量的应用
>>> def Fun1():
x = 5
def Fun2():
x *= x
return x
return Fun2()
>>> Fun1()
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
Fun1()
File "<pyshell#46>", line 6, in Fun1
return Fun2()
File "<pyshell#46>", line 4, in Fun2
x *= x
UnboundLocalError: local variable 'x' referenced before assignment
>>> def Fun1():
x = [5]
def Fun2():
x[0] *= x[0]
return x[0]
return Fun2()
>>> Fun1()
25
例2: " nonlocal " 关键字的应用
>>> def Fun1():
x = 5
def Fun2():
nonlocal x
x *= x
return x
return Fun2()
>>> Fun1()
25
5. lambda函数的应用
例1:
>>> def ds(x):
return 2 * x + 2
>>> ds(2)
6
>>> lambda x : 2 * x + 2
<function <lambda> at 0x0000023767B8D048>
>>> g = lambda x : 2 * x + 2
>>> g(5)
12
6. filter(function or None, iterable) 第二个参数迭代器在第一个参数中运算,返回结果为真的可迭代对象
>>> def odd(x):
return x % 2
>>> temp = range(10)
>>> show = filter(odd, temp)
>>> list(show)
[1, 3, 5, 7, 9]
或者
list(filter(lambda x : x % 2, range(10)))
[1, 3, 5, 7, 9]
7. 映射函数 map() 表示将第二个可迭代对象的每一个参数带到第一个函数中计算,结果返回每个计算后的可迭代对象
>>> list(map(lambda x : x * 2, range(10)))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]