函数内修改全局变量
>>> def fun():
count=5
print('不能改变')
>>> count=10
>>> print(count)
10
>>> fun()
不能改变
>>> print(count)
10
>>> def fun():
global count
count=5
print('改变了')
>>> count =10
>>> fun()
改变了
>>> print(count)
5
内嵌函数
def fun1():
print('fun1运行……')
def fun2():
print('fun2运行……')
fun2()
fun1()
fun1运行……
fun2运行……
闭包
>>> def funX(x):
def funY(y):
return x*y
return funY
>>> i = funX(8)
>>> i(4)
32
>>> def fun1():
x=5
def fun2():
x *= x
return x
return fun2()
>>> fun1()
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
fun1()
File "<pyshell#17>", line 6, in fun1
return fun2()
File "<pyshell#17>", line 4, in fun2
x *= x
UnboundLocalError: local variable 'x' referenced before assignment
>>>
>>> def fun1():
x = 5
def fun2():
nonlocal x
x *= x
return x
return fun2()
>>> fun1()
25
匿名函数
>>> def X(x):
return x * 2
>>> X(2)
4
g = lambda x : x * 2
>>> a(2)
4
过滤
>>> list(filter(None,[1,0,2,False]))
[1, 2]
>>> list(filter(lambda x : x % 2 ,range(10)))
[1, 3, 5, 7, 9]
遍历
>>> list(map(lambda x : x * x,range(10)))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
函数递归
def fun(n):
if n == 1:
return 1
else:
return n * fun(n-1)
num = int(input("num:"))
print(fun(num))