python_入门_第八天

函数内修改全局变量

# 正常情况下函数不能改变全局变量
>>> def fun():
    count=5
    print('不能改变')
>>> count=10
>>> print(count)
10
>>> fun()
不能改变
>>> print(count)
10
# 添加global可以在函数内修改全局变量
>>> 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
>>>
# 内嵌函数修改外边变量的方法 通过nonlocal函数
>>> 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

过滤

# filter函数 参数2执行参数1 输出不为False或0的值 若无参数1直接分析参数二的值是否为False或0
>>> 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))

猜你喜欢

转载自blog.csdn.net/m0_37416991/article/details/81177790