使用 break 和 continue 控制循环流程
Python 提供了 break 和 continue 两个语句来改变循环的正常流程。
break 语句会立即终止其所在的循环。程序执行会跳转到循环之后的第一个语句。
我们来看一个例子。打开 break_example.py 文件并添加这段代码,它会在满足特定条件时停止循环:
## Iterate through numbers from 0 to 9
for i in range(10):
## If i is 5, the 'if' condition becomes True
if i == 5:
print(f"Breaking loop at i = {i}")
## The break statement exits the loop immediately
break
print(i)
print("Loop finished.")
保存文件并运行它:
python break_example.py
输出将是:
0
1
2
3
4
Breaking loop at i = 5
Loop finished.
当 i 变为 5 时,循环停止了,数字 5 到 9 从未被打印出来。
continue 语句会跳过当前迭代的剩余部分,直接进入下一次迭代。
让我们看看如何使用 continue 来跳过打印特定数字。打开 continue_example.py 文件并添加以下代码:
## Initialize a counter
count = 0
## Loop while count is less than 10
while count < 10:
count += 1
## If count is 5, the 'if' condition becomes True
if count == 5:
print(f"Skipping iteration at count = {count}")
## The continue statement skips the rest of this iteration
continue
## This line is skipped when count is 5
print(count)
print("Loop finished.")
保存文件并运行它:
python continue_example.py
输出将是:
1
2
3
4
Skipping iteration at count = 5
6
7
8
9
10
Loop finished.
在这种情况下,当 count 为 5 时,执行了 continue 语句。这导致该次迭代中的 print(count) 语句被跳过,循环进入下一次迭代,此时 count 变为 6。