计算机科学 3 第 67-69 关
LOOPING
🎛️

循环控制:continue & break

智能循环开关

⏭️ Continue (跳过)
🛑 Break (停止)
⏭️

Continue:跳过本轮

continue 就像循环的“跳过按钮”。

当遇到它时,循环会立即放弃当前这轮剩下的工作,直接开始下一轮。

if apple.isBad:
  continue # 坏苹果?不要了,下一个!
pack(apple) # 只有好苹果才会执行到这
"就像检查苹果,看到坏的直接扔掉,看下一个!"
🚮
📦
🛑

Break:循环出口

break 就像循环的“紧急出口”。

当遇到它时,循环会彻底停止,不再继续执行。

while True:
  count += 1
  if count > 20:
    break # 够了!停!
"就像数糖果,数满20颗就收工回家!"
0
Limit: 10
BREAK!
🧪

实战 I:聪明的收集者

使用 continue 过滤掉不想要的情况:

while True:
  item = findItem()
  # 1. 没东西? 跳过
  if not item: continue
  # 2. 是毒药? 跳过
  if item.type == "poison": continue
  # 安全!去拿
  moveXY(item.pos.x, item.pos.y)
找到物品
⬇️
是毒药吗?
↙️ 是 (continue)
否 ↘️
去收集
⤴️ 回到开头
⚔️

实战 II:限时战斗

使用 break 在时间到时退出战斗循环:

while True:
  # 检查时间
  if hero.time > 30:
    break # 时间到,撤退!

  # 战斗逻辑...
  attack(enemy)

退出循环后,去执行下一步(比如移动到出口)。

🚪
🧠

思维训练:安检模式

条件提前返回 (Early Return)

尽早发现不符合条件的情况并 continue,就像安检。

# ❌ 嵌套太深 (像俄罗斯套娃)
if enemy:
  if type != "burl":
    if type != "yak":
      attack()
# ✅ 扁平清晰 (像安检门)
if not enemy: continue
if type == "burl": continue
attack()
🏃
🚧
🚧
🏁

遇到路障直接跳过,最后才是终点

💡

布尔逻辑组合

使用 orand 组合条件,让判断更强大。

# 如果是 Burl 或者 Yak (都是好人)
if type == "burl" or type == "yak":
  continue # 跳过不打
# 时间不够 或 钱够了
if time > 30 or gold > 20:
  break # 停止
🌲 / 🐂
SKIP
🎓

控制大师口诀

"continue 是跳过,
坏的不要,看下一个!"
"break 是出口,
任务完成,立马就走!"
🚦