python学习第六天 7.11
程序员文章站
2024-03-16 13:30:22
...
-
global 关键字:将局部变量变成全局变量。
-
内嵌函数:
-
闭包:
>>> def funX(x):
def funY(y):
return x*y
return funY
>>> i=funX(8)
>>>
>>> i
<function funX.<locals>.funY at 0x000002655EB2C550>
>>> i(5)
40
>>> funX(8)(5)
40
>>> funy(5)
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
funy(5)
NameError: name 'funy' is not defined
- nonlocal表达式:用于申明内部函数的变量作用域可拓展至内部函数外部至定义的函数中(类似于global表达式)
>>> def fun1():
x=5
def fun2():
x*=x
return x
return fun2()
>>> fun1()
Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
fun1()
File "<pyshell#35>", line 6, in fun1
return fun2()
File "<pyshell#35>", 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
- lambda表达式:
>>> def ds(x):
return 2*x+1
>>> ds(5)
11
>>> lambda x:2*x+1
<function <lambda> at 0x000002655F344E50>
>>> g=lambda x:2*x+1
>>> g(5)
11
- filter语句:过滤器(把任何非True的内容过滤掉)
>>> def odd(x):
return x%2
>>> show=filter(odd,range(0,10))
>>> list(show)
[1, 3, 5, 7, 9]
>>> list(filter(lambda x:x%2,range(0,10)))
[1, 3, 5, 7, 9]
- map语句:映射(把函数内的所以参数进行加工之后进行返回)
>>> list(map(lambda x:x*3,range(0,10)))
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
- 递归算法:函数对自身进行调用且设置了正确的返回值
def factorical(n):
if n==1:
return 1
else:
return n*factorical(n-1)
number=int(input('请输入一个正整数:'))
result=factorical(number)
print("%d 的阶乘是:%d" %(number,result))
请输入一个正整数:5
5 的阶乘是:120