这个系列主要是文档与自己的用法之间的出入的反思,以后不光需要多练,仍需要更多的反思
More Control Flow Tools
- 如果在循环当中对序列进行修改,不会报错,但是肯定会有各种各样的问题
建议: for循环的序列应该是原序列的copy,推荐用[:]来复制,这样易读性更佳
>>> for w in words[:]: # Loop over a slice copy of the entire list.
... if len(w) > 6:
... words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']
- py3中,range直接返回的就是迭代对象
- 循环语句当中也可以有else子句,用在循环迭代结束之后
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
pass语句的用处
占位符,最小类,while truefor vs while
个人认为对象是个序列的时候用for
其他数据结构算法时while用的比较多
以可读性为准如果一直执行到整个函数结束还没有碰到 return 语句,也返回 None。
函数的默认值只计算一次
i = 5
def f(arg=i):
print(arg)
i = 6
f()
- 函数的默认值是个可变对象的时候,推荐这样写
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
- 关键字参数必须写在位置参数之后
- (name必须出现在*name之前)
- 学会使用文档字符串
>>> def my_function():
... """Do nothing, but document it.
...
... No, really, it doesn't do anything.
... """
... pass
...
>>> print(my_function.__doc__)
Do nothing, but document it.
No, really, it doesn't do anything.
- 实际项目中多使用lambda
dt2str = lambda dt: dt.strftime('%Y-%m-%d %H:%S:%M') - 学会是用函数的文档
my_function.__doc__