Thoroughly get to know the python function 2

First, variable scope

Scope of a variable called function code range of the variable , the variable name in different scopes may be the same, independently of each other.

  • Local variables Common variables inside a function defined only work within the function. After the end of the function execution, local variables automatically deleted, no longer can be used.
    Reference is faster than global variables local variables, priority should be given to use.

  • Global variables can be defined by the keyword global. It is divided into two situations:
    1. A variable defined outside a function, if required for this variable assignment within a function, and you want to reflect the result of the assignment to function outside, can be declared as global using global variables within a function .
    2. If a variable is not defined outside of the function may be directly defined inside a variable function of global variables, after execution of the function will add a new global variables.

  • A reference value of a variable within the function only and not assign it a new value, if such an operation can be performed, then the variables (implicit) global variables .

  • If any of the operating position of the variable a promising new value in the function, the variable is deemed to be (implicit) local variable , unless explicitly declared with the keyword in the global function.

>>> def demo():
    global x                 #x被声明为全局变量
    x = 3
    y = 4
    print(x,y)

>>> x = 5
>>> demo()
3  4
>>> x
3               #如果把global x删去则输出5,因为此时上边定义的x为局部变量,只在demo()函数内生效
>>> y           #因为y是局部变量所以在函数外调用会报错
NameError: name 'y' is not defined
>>> del x         #把x删掉
>>> x
NameError: name 'x' is not defined
>>> demo()
3  4
>>> x
3
>>> y
NameError: name 'y' is not defined
  • If local variables and global variables with the same name, then the local variable will conceal the global variable of the same name in their scope, but local variables declared inside a function does not affect the external function .
>>> def demo():
    x = 3         #创建了局部变量,并自动隐藏了同名的全局变量	

>>> x = 5
>>> x
5                #函数内部声明的局部变量不会影响函数外部
>>> demo()
>>> x             #函数执行不影响外面全局变量的值
5

Two, lambda expressions

  • lambda expressions can be used to declare an anonymous function , the function name is not a function of a small temporary use, especially suitable for the needs of another function parameters as a function of the occasion. You can also define named function.
  • lambda expressions can only contain a single expression , the calculation result of the expression can be seen as the return value of the function, compound statements are not allowed, but in an expression can call other functions.
>>> f = lambda x, y, z: x+y+z        #可以给lambda表达式起名字
>>> f(1,2,3)                         #像函数一样调用
6
>>> g = lambda x, y=2, z=3: x+y+z    #参数默认值
>>> g(1)
6
>>> g(2, z=4, y=5)                   #关键参数
11
>>> L = [1,2,3,4,5]
>>> print(list(map(lambda x: x+10, L)))        #模拟向量运算
[11, 12, 13, 14, 15]
>>> L
[1, 2, 3, 4, 5]
>>> data = list(range(20))           #创建列表
>>> data
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> import random
>>> random.shuffle(data)             #打乱顺序
>>> data
[4, 3, 11, 13, 12, 15, 9, 2, 10, 6, 19, 18, 14, 8, 0, 7, 5, 17, 1, 16]
>>> data.sort(key=lambda x: x)       #和不指定规则效果一样
>>> data
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> data.sort(key=lambda x: len(str(x)))     #按转换成字符串以后的长度排序
>>> data
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> data.sort(key=lambda x: len(str(x)), reverse=True)     #降序排序,两位数在前
>>> data
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Third, the generator function

  • Contains a yield statement function can be used to create the generator object, this function is also called a generator function .
  • yield statement and return statement effect similar values are used to return from the function. The difference is that the return statement, return statement will be executed once the end of the function operation immediately, but after each execution returns to yield a value statement and suspend or hang behind the implementation of the code , the next object generator by the __next __ ( ) method, built-in function next (), for generating a resume execution when the object to loop through elements or otherwise explicit "request" data.
  • Generator having a lazy evaluation characteristics, suitable for large data processing.
#编写并使用能够生成斐波那契数列的生成器函数。
>>> def f():
    a, b = 1, 1            #序列解包,同时为多个元素赋值
    while True:
        yield a            #暂停执行,需要时再产生一个新元素
        a, b = b, a+b      #序列解包,继续生成新元素

>>> a = f()                #创建生成器对象
>>> for i in range(10):    #斐波那契数列中前10个元素
    print(a.__next__(), end=' ')
1 1 2 3 5 8 13 21 34 55 

>>> for i in f():         #斐波那契数列中第一个大于100的元素
    if i > 100:
        print(i, end=' ')
        break

144
>>> a = f()               #创建生成器对象
>>> next(a)               #使用内置函数next()获取生成器对象中的元素
1
>>> next(a)               #每次索取新元素时,由yield语句生成
1
>>> a.__next__()          #也可以调用生成器对象的__next__()方法
2
>>> a.__next__()
3
Published 108 original articles · won praise 332 · views 30000 +

Guess you like

Origin blog.csdn.net/zag666/article/details/105073301