在Python中,跳出循环通常使用`break`语句。当程序执行到`break`语句时,当前循环会立即终止,程序会继续执行循环后面的代码。如果需要从嵌套循环中跳出,可以使用一个状态变量来控制循环的退出。
使用`break`和`continue`
使用break跳出循环
for i in range(10):
if i % 2 == 0:
break
print(i)
使用continue跳过当前循环
for i in range(10):
if i % 2 == 0:
continue
print(i)
使用自定义异常
class Getoutofloop(Exception):
pass
try:
for i in range(5):
for j in range(5):
if i == j == 2:
raise Getoutofloop()
else:
print(i, '----', j)
except Getoutofloop:
pass
使用函数返回
def test():
for i in range(10):
print(i)
if i == 5:
return
test()
使用`for...else...`语句
for i in range(10):
if i == 5:
break
else:
print("Loop completed without breaking")
这些方法可以帮助你在Python中根据不同的条件跳出循环。