使用 break 和 continue 控制循环执行
注释
有关更多详细信息,请参阅 “文本和图像 ”选项卡!
尽管循环旨在重复代码块,但有时需要更精细地控制循环的执行方式。 例如,你可能希望提前退出循环,或者跳过某些迭代,而不会完全停止循环。
Python提供了使用两个语句对循环执行的精确控制:break和continue。
中断 - 提前退出循环
无论条件如何,语句 break 都会立即结束循环。 它告知Python停止执行循环,并在循环块之后转到下一行代码。 例如:
for count in range(10):
if count == 5:
break
print(count)
print("Loop ended.")
输出:
0
1
2
3
4
Loop ended.
行顺序很重要。 语句 break 必须在要检查的条件 之后 ,但在要跳过的代码 之前 。 在上面的示例中,循环在打印 5 之前停止。
继续 - 跳到下一次迭代
该continue语句告知Python跳过其下方的其余代码,并立即跳转到循环的下一次迭代。 例如,你可能希望跳过序列中的特定数字:
for count in range(6):
if count == 3:
continue
print(count)
输出:
0
1
2
4
5
在此示例中,continue语句强制Python放弃print()下面的行,并跳转到循环的下一次迭代。 如果要忽略某些迭代而不停止整个循环,则此语句非常有用。
使用 break 控制 while 循环
这两个关键字在 while 循环中的作用方式相同。 将 while 循环与 break 语句组合在一起是处理不可预知的用户输入时使用的常见模式。
例如,你可能希望继续运行代码,直到用户键入要退出的特定单词:
while True:
user_input = input("Type 'exit' to stop the loop: ")
if user_input.lower() == "exit":
break
print(f"You entered: {user_input}")
print("Goodbye!")
while True 创建将永远运行的循环 —break 是退出循环的唯一方法。 这种模式允许你反复提示用户,并在用户明确表示要停止时优雅地退出。
在 while 循环中使用 continue 语句
在 continue 循环中使用 while 需要仔细注意循环的条件。 如果您在不修改条件的情况下使用 continue,则可能会导致无限循环。 例如:
current_slot = 0
while current_slot < 5:
current_slot += 1 # CRUCIAL: Increment happens right at the start of the lap
if current_slot == 3:
print(f"Skipping item slot {current_slot}.")
continue # Aborts the rest of this lap and jumps back to the top
# This processing code is skipped when current_slot is 3
print(f"Successfully processed item in slot {current_slot}.")
print("Inventory scan complete!")
在此示例中,循环在每个迭代的开头递增 current_slot 。 当语句达到 3 时, continue 该语句将跳过处理代码并跳转回循环的顶部。 如果将递增语句放在 continue 之后,循环将永远无法达到 5,并且会无限循环。
在 while 循环中使用 continue 时,请务必始终在 continue 语句之前更新条件,以避免造成无限循环。
在循环中使用 else
当 for 或 while 循环正常完成时(即未遇到 break 语句),可以使用 else 块在循环结束后执行代码。 例如:
color = "blue"
for i in range(3):
user_input = input("Guess my favorite color: ")
if user_input.lower() == color:
print("You guessed it!")
break
else:
print(f"Sorry, the correct answer is {color}.")