Skip to content

跳转语句

有些时候,我们想要提前结束循环,这时候就需要用到跳转语句

  • break:跳出整个循环

  • continue:跳出当前轮次循环

break

break关键字用于跳出整个循环,当你想在某种情况下直接中断循环、马上跳出去就需要使用它

即使 while 的条件永远不会变成 false,只要遇到 break,循环立刻就结束,程序会从循环块的下一行继续执行

gdscript
var count = 0
while true:
    count += 1
    print("current count:", count)
    if count == 5: 
        break
print("loop ended")
  • 想想看,上面这段代码会是一个无限循环吗?它会循环几次?

    虽然我们写的是while true,但这段代码只会执行五次,因为当 count == 5 的时候,我们手动 break

    输出会是这样的:

    gdscript
    current count: 1
    current count: 2
    current count: 3
    current count: 4
    current count: 5
    loop ended

在嵌套循环的情况下,break只会结束其所在层级的循环,在内层循环使用break不会结束外层的循环

gdscript
for i in 3:
    for j in 10:
        if j == 2:
            break
        print(i, ", ", j)
    print()
gdscript
0, 0
0, 1

1, 0
1, 1

2, 0
2, 1

break关键字常用于:

  • 找到目标后提前退出

  • 防止死循环(无限循环)这样的意外情况

下面的代码演示了如何获取字符串中第一个指定字符出现的位置并跳出循环

gdscript
var index = -1
var found = false
for c in "Hello World!":
    index += 1
    if c == " ":
        found = true
        break
index = -1 if not found else index
print("space at index:", index)

continue

continuebreak关键字不同,它用于结束当前这一轮的循环执行,对于while循环,它会马上跳回去重新判断条件,如果为true,则开始下一轮

continue不能中止无限循环

continue可以和break一起使用

gdscript
var count = 0
while count < 10:
    count += 1
    if count % 2 != 0:
        continue
    print("The current count is even:", count)
  • 想想看,上面的代码会输出几则信息呢?

    每次循环 count += 1,从 1 加到 10

    如果 count 是奇数(也就是 count % 2 != 0),就 continue,跳过 print

    所以只有 偶数会被打印出来

    输出是这样的:

    gdscript
    The current count is even2
    The current count is even4
    The current count is even6
    The current count is even8
    The current count is even10

    一共输出了 5 条信息

在嵌套循环的情况下,continue只会结束其所在层级的循环的本轮循环,在内层循环使用continue不会影响外层的循环

gdscript
for i in 3:
    for j in 4:
        if j == 2:
            continue
        print(i, ", ", j)
    print()
gdscript
0, 0
0, 1
0, 3

1, 0
1, 1
1, 3

2, 0
2, 1
2, 3

continue关键字常用于:

  • 过滤筛选数据

  • 快速进入下一轮循环,避免冗余判断或操作

下面的代码演示了如何使用continue获取字符串中指定字符出现的次数

gdscript
var count = 0
for c in "Hello World!":
    if c != "o":
        continue
    count += 1        
    
print(count, " characters: 'o' were found")

练习

  1. 给定一个字符串,使用 forcontinue 来数出其中有多少个空格 " "

  2. 使用循环找出字符串中第一个出现 "!" 的位置(下标),找到后立刻停止循环

  3. 使用循环打印 1~100 中第一个能被 7 整除的数字(break)

  4. 使用循环打印 1~20 中所有不是 5 的倍数的数字(continue)