while 可以说是最常用到的回圈函数之一了,最要 while 后面接的条件达成,回圈就会一直执行下去,直到出现了于条件不相符合的其他条件时,整个回圈才会终止。
一般格式
首行与测试表达式占有一列或是多列缩进语句的主体,可能伴随一个 else 去规范超出 while 后面表达式规范的情况,下面举例:
>>> x = 'spam'
>>> while x:
print(x)
x = x[1:]
spam pam am m # this loop is making a condition if the string exists, repeat the execution.
>>> a = 0 ; b = 10
>>> while a < b:
print(a)
a += 1
0 1 2 3 4 5 6 7 8 9
break:跳出最近所在的循环语句
continue:跳到当下循环的开头(不跳离该循环)
pass:什么事也不做,就空占着位置,多是为了维持语句的正确性用的
else:只有当循环正常离开时才会被执行,如果是 break 强迫停止的话,那也就跟着一起跳过了:
>>> while a < b:
a += 1
if a == 3:
break
print(a)
>>> else:
print(a)
1 2 # nothing will be printed further
>>> while a < b:
a += 1
if a == 3:
continue
print(a)
>>> else:
print(a)
1 2 4 5 6 7 8 9 10 10 # 3 will not be printed
for 循环
一个通用的 "序列" 选代器,可以 loop through 任何有序的序列对象元素,包含了字符串,列表,元组等等。在序列没有结束前,for 回圈就会不断的重复动作,当循环到了最后一个元素,并且执行完毕后,就会自动停止回圈:
>>> sum = 0
>>> for x in [1, 2, 3, 4]: # list is a sequential datatype
sum = sum + x
>>> sum
10
>>> s = 'lumberjack'
>>> for x in S:
print(x)
l u m b e r j a c k
看到 for 和 in 中间的那个变量 x,其实他是一个随便怎么命名的 variable,只存在在当下 for 这个回圈中,也不用宣告,不用赋值,直接爱叫什么就叫什么名字。
如果更进阶一点,for loop 里面还可以套一个 for loop,把第一个 for loop 循环的元素独立的再拿来做其他循环:
>>> items = ['aaa', 111, (4, 5), 2.01]
>>> tests = [(4, 5), 3.14]
>>> for x in tests:
for y in items:
if x == y:
print(x, 'was found')
else:
print(x, 'was not found')
'aaa' was not found
111 was not found
(4, 5) was found
3.14 was not found
上面例子也可以用作扫描文档的好方法,也是老手常用的手段。
有些时候我们希望能够把不同 object 合在一起 loop,或者是对他们编号,可以这样:
>>> N = [1, 2, 3, 4]
>>> M = [5, 6, 7, 8, 9, 10]
>>> zip(N, M) # zip will cut off the rests of data
[(1, 5), (2, 6), (3, 7), (4, 8)]
>>> map(None, N, M) # map will satisty them all
[(1, 5), (2, 6), (3, 7), (4, 8), (None, 9), (None, 10)]
>>> s = 'spam'
>>> for offset, item in enumerate(s):
print(offset, item)
0 s
1 p
2 a
3 m
列表解析
列表真的是 for 的好朋友,他们非常搭配,可以彼此协调出很多新花样,例如可以统一为里面的元素一起加个 10:
>>> L = [1, 2, 3, 4, 5]
>>> for i in range(len(L)):
L[i] += 10
>>> L
[11, 12, 13, 14, 15]
# or there is another easier way
>>> L = [x + 10 for x in L]
>>> L
[11, 12, 13, 14, 15]
很多时候列表解析会与文件读取结合,因为一般我们用 function 都出来的文件,都是一行一行为一个 unit 的放在 list 其中一个元素里面,任何需要读取文件里面所有东西的功能,肯定会跟 for 回圈结合使用。