while的格式如下:
while <test>:
<statements1>
else:
<statements2>
1.使用break
>>> a = 1; b = 3
>>> while a:
b -= 1
if b == 0:
print('b equals to 0')
break
b equals to 0
2.使用continue
与break类似。这里不再举例。
3.pass
意味着没什么事要做。先放在这。
在try-catch中有可能会用。但是也不是必须的。
pass重在提醒“这边我先放着,以后还会修改”的意思。
4.使用break--else结构
x = y // 2 # For some y > 1
while x > 1:
if y % x == 0: # Remainder
print(y, 'has factor', x)
break # Skip else
x -= 1
else: # Normal exit
print(y, 'is prime')
5.for loop
for <target> in <object>:
<statements>
else:
<statements>
由于之前频繁使用。这也不再讲解。
6.range(n)
使用range函数,配合for,产生一个递增遍历。
>>> for i in range(4):
print(i)
0
1
2
3
>>>
对tuple的遍历。
T = [(1, 2), (3, 4), (5, 6)]
for (a, b) in T:
print (a, b)
其它的遍历例子。
>>>for ((a, b), c) in [([1, 2], 3), ['xy', 6]]:
>>> print (a, b, c)
(1, 2, 3)
('x', 'y', 6)
3.0甚至还支持下面的遍历或赋值。
a, *b, c = (1, 2, 3, 4)
7.用zip合并list。
>>>l1 = [1, 2, 3, 4]
>>>l2 = [5, 6, 7, 8]
>>>for (x, y) in zip(l1, l2):
>>> print (x, y)
(1, 5)
(2, 6)
(3, 7)
(4, 8)
8.产生index的for循环。
>>>S = 'spam'
>>>for (offset, item) in enumerate(S):
>>> print offset, item
0 s
1 p
2 a
3 m
end.