作用:当语句要求不希望任何命令或代码来执行时使用
说明:
if 1:
pass
作用:退出循环 注意:只能跳出距离最近的for或者while循环
for
for x in range(10):
if x == 5:
# 结束循环(跳出循环)
break
print("x = %d"%x)
<span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> range(<span class="hljs-number">3</span>):
<span class="hljs-keyword">for</span> y <span class="hljs-keyword">in</span> range(<span class="hljs-number">5</span>):
<span class="hljs-keyword">if</span> y == <span class="hljs-number">3</span>:
<span class="hljs-keyword">break</span>
print(<span class="hljs-string">"******"</span>, y)
print(<span class="hljs-string">"-------"</span>, x)
while
while循环语句可以有else子句,表达式为假时会被执行,但是使用break终止while循环后else中的子句不执行
num = <span class="hljs-number">0</span>
<span class="hljs-keyword">while</span> num < <span class="hljs-number">8</span>:
print(<span class="hljs-string">"num = %d"</span>%num)
num += <span class="hljs-number">1</span>
<span class="hljs-keyword">if</span> num == <span class="hljs-number">8</span>:
<span class="hljs-keyword">break</span>
<span class="hljs-keyword">else</span>:
print(<span class="hljs-string">"--------else"</span>)
作用:跳过本次循环后面的剩余语句,然后继续下一次循环 注意:只能跳过距离最近的for或者while循环
for
for x in range(10):
if x == 5:
continue
print("x = %d"%x)
while
num = 0
while num < 10:
if num == 5:
num += 1
continue
print("num = %d"%num)
num += 1