1、并行迭代————内置函数zip()
>>> names = ['ame','burning','yyf','longdd','dd']
>>> ages = [22,23,24,25,26]
>>> for name,age in zip(names,ages):
print(name,' is ',age,' years old.')
ame is 22 years old.
burning is 23 years old.
yyf is 24 years old.
longdd is 25 years old.
dd is 26 years old.
#当两个序列长度不同时,以最短序列用完就停止
方法enmuerate()能迭代索引-值对,索引起始值可选
>>> w = ['q','w','e','r','t']
>>> for index,i in enumerate(w): #默认从0开始
print(index,i)
0 q
1 w
2 e
3 r
4 t
>>> for index,i in enumerate(w,2): #索引起始值为2
print(index,i)
2 q
3 w
4 e
5 r
6 t
2、关于exec和eval
函数exec将字符串作为代码执行
>>> exec("print('Hello, world!')") #注意符号
Hello, world!
pass
3、判断某个对象能否调用,用内置函数callable
>>> import math
>>> x = 1 #不是函数
>>> y = math.sqrt
>>> callable(x)
False
>>> callable(y)
True
4、文档字符串
>>> def square(x):
'Calculates the square of the number x'
return x*x
>>> square.__doc__
'Calculates the square of the number x'
5、收集参数
* 收集多余的值组成一个元组,若没有可供收集的参数,就创建一个空元组(* 不收集关键字参数)
>>> def param(x,*y,z):
print(x,y,z)
>>> param(1,2,3,4,5,6,z=7)
1 (2, 3, 4, 5, 6) 7
** 收集关键字参数,返回一个字典
>>> def pa(**c):
print(c)
>>> pa(q=1,w=2,e=3)
{'q': 1, 'w': 2, 'e': 3}
- 和 ** 可以组合使用:
>>> def gaa(x,y,z=3,*one,**two):
print(x,y,z,one,two)
>>> gaa(1,3,2,11,22,33,f=11,d=22,g=33)
1 3 2 (11, 22, 33) {'f': 11, 'd': 22, 'g': 33}
6、作用域
变量可以视为指向值的名称,如执行赋值语句x=1后,变量x指向值1。这类似于字典,但是这是一个“ 看不见的字典 ”。这种“ 看不见的字典 ” 称为命名空间或者作用域。除了全局作用域外,每个函数调用都将创建一个。
若想在函数中访问全局变量,如下:
>>> def combine(parameter):
print(parameter + external)
>>> external = 'berry'
>>> combine('straw')
strawberry
虽然可以读取全局变量的值,但是这样访问全局变量是众多BUG的根源,务必谨慎使用
当局部变量和要访问的全局变量同名时,全局变量会被局部变量遮挡,导致无法访问,这时要使用globals(),它返回一个包含全局变量的字典(locals返回一个包含局部变量的字典)
>>> def com(parameter):
print(parameter + globals()['parameter'])
>>> parameter = 'berry'
>>> com('straw')
strawberry
7、作用域嵌套
嵌套:一个函数放在另一个函数内,多用于使用一个函数来创建另一个函数。
>>> def multiplier(factor):
def multiplyByFactor(number):
return number ** factor
return multiplyByFactor
>>> double = multiplier(2)
>>> double(3)
9
>>> double(5)
25
这里外面的函数返回里面的函数,返回的结果是一个函数。
重要的是,返回的函数能够访问其定义所在的作用域,即它携带着自己所在的环境和相关的局部变量。
每当外部函数被调用时,都将重新定义内部的函数,而变量factor的值也可能不同。
闭包
pass