第十三篇:while

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.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值