循环
while 循环
while <condition>:
<statesments>
for 循环
for <variable> in <sequence>:
<indented block of code>
continue 语句
遇到 continue 的时候,程序会返回到循环的最开始重新执行。
例如在循环中忽略一些特定的值:
values = [7, 6, 4, 7, 19, 2, 1]
for i in values:
if i % 2 != 0:
# 忽略奇数
continue
print i/2
3
2
1
break 语句
遇到 break 的时候,程序会跳出循环,不管循环条件是不是满足:
else语句
与 if 一样, while 和 for 循环后面也可以跟着 else 语句,不过要和break一起连用。
当循环正常结束时,循环条件不满足, else 被执行;
当循环被 break 结束时,循环条件仍然满足, else 不执行。
values = [1,2,3,5]
for x in values:
if x > 0:
print 'find',x
break
else:
print 'All number big than 0'
find 1
执行
values = [-0.5,-1,-5]
for x in values:
if x > 0:
print 'find',x
break
else:
print 'All number small than 0'
All number small than 0

浙公网安备 33010602011771号