add = "http://c.biancheng.net/python/,http://c.biancheng.net/shell/"
# 一个简单的for循环
for i in add:
if i == ',' :
#终止循环
break
print(i,end="")
print("\n执行循环体外的代码")
运行结果为:
http://c.biancheng.net/python/
执行循环体外的代码
注意,通过前面的学习我们知道,for 循环后也可以配备一个 else 语句。这种情况下,如果使用 break 语句跳出循环体,不会执行 else 中包含的代码。举个例子:break 语句一般会结合 if 语句进行搭配使用,表示在某种条件下跳出循环体。
add = "http://c.biancheng.net/python/,http://c.biancheng.net/shell/"
for i in add:
if i == ',' :
#终止循环
break
print(i,end="")
else:
print("执行 else 语句中的代码")
print("\n执行循环体外的代码")
程序执行结果为:
http://c.biancheng.net/python/
执行循环体外的代码
add = "http://c.biancheng.net/python/,http://c.biancheng.net/shell/"
for i in range(3):
for j in add:
if j == ',':
break
print(j,end="")
print("\n跳出内循环")
程序执行结果为:
http://c.biancheng.net/python/
跳出内循环
http://c.biancheng.net/python/
跳出内循环
http://c.biancheng.net/python/
跳出内循环
add = "http://c.biancheng.net/python/,http://c.biancheng.net/shell/"
#提前定义一个 bool 变量,并为其赋初值
flag = False
for i in range(3):
for j in add:
if j == ',':
#在 break 前,修改 flag 的值
flag = True
break
print(j,end="")
print("\n跳出内循环")
#在外层循环体中再次使用 break
if flag == True:
print("跳出外层循环")
break
可以看到,通过借助一个 bool 类型的变量 flag,在跳出内循环时更改 flag 的值,同时在外层循环体中,判断 flag 的值是否发生改动,如有改动,则再次执行 break 跳出外层循环;反之,则继续执行外层循环。
http://c.biancheng.net/python/
跳出内循环
跳出外层循环
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有