通常,循环会不断的执行代码块,直到条件为假或者使用完序列中的所有元素。但在有些情况下,你可能想中断循环,开始新迭代或者直接结束循环。
1、break:直接跳出循环,执行后面的代码。假设找到小于100的最大平方值。
from math import sqrt;
for n in range(99,0,-1):
root=sqrt(n);
if root==int(root):
print(n)
break
运行结果:
81
2、continue:语句continue没有break用的多,它结束当前迭代,并跳到下一次迭代开头。这意味着跳过循环中余下的语句,但不结束循环。
3、循环语句中的else:
from math import sqrt;
for n in range(99,80,-1):
root=sqrt(n);
if root==int(root):
print(n)
break;
else:
print("didnot find it")
运行结果:
81
from math import sqrt;
for n in range(99,81,-1):
root=sqrt(n);
if root==int(root):
print(n)
break;
else:
print("didnot find it")
运行结果:
didnot find it
3、pass:占位符。即什么都不用做。
4、del 删除。
x=["hello","world"]
y=x;
print(x);
print(y)
del x;
print(y)
运行结果:
['hello', 'world']
['hello', 'world']
['hello', 'world']
你可能认为删除x,同时也删除y。但删除x对你没有任何影响,因为你只删除名称x,而没有删除列表本身。