- 在Python循环语句中,复杂的条件可能会嵌套break,continue或者pass
- break用于终止整个循环语句
- continue用于跳出当前循环,并且执行下一次循环
- pass语句用于占位,不做任何操作,保持结构的完整性
- 列表推导式用于构建新的数据序列
s=0
for i in range(1,101):
s+=i
if i>=10:
break
count=0
while count<10:
count+=1
if count%3==0:
print(count)
break # count=3时,终止循环
else:
print(count)
# 输出 1 2 3
count=0
while count<10:
count+=1
if count%3==0:
print(count)
continue # count=3,6,9时,跳过循环
else:
print(count)
# 输出 1 2 4 5 7 8
count=0
while count<10:
count+=1
if count%3==0:
print(count)
pass
else:
print(count)
# 输出 1 2 3 4 5 6 7 8 9
squares=[]
for x in range(10):
squares.append(x**2)
[x**2 for x in range(10)]
vec=[-9,8,7,6,8,-4,4]
[x**0.5 for x in vec if x>0]
a=[6,7,9,-6,5,4,'one']
total=0
for i in a:
try:
total+=i
except:
pass # 当加‘one’时,会捕获到异常,然后会执行except下面的语句