Python学习记录(11)

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]

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Python史上最全开发总结(转自静熙老师哈哈哈) 两本不错的书: 《Python参考手册》:对Python各个标...
    春风在抱阅读 854评论 1 4
  • 写在前面的话 代码中的# > 表示的是输出结果 输入 使用input()函数 用法 注意input函数输出的均是字...
    FlyingLittlePG阅读 3,234评论 0 9
  • 一、函数 1.函数概述 1.1认识函数 需求:求圆的面积s = π * r ** 2c = math.sqrt(a...
    hollow_02f9阅读 777评论 0 2
  • 第0024张卡片 常听人说,孩子是父母的复印件。“复印件”出了问题,按理来说,应该从“原件”身上找问题,可大多数时...
    骆驼教练阅读 588评论 0 0
  • 今天是感恩节。9:56父亲正在手术中。 我以前以为手术中的等待是最难熬的,现在我的心中反而是最坦然的。母亲的承受力...
    吴佟阅读 256评论 1 0

友情链接更多精彩内容