geekdoc-python-zh/docs/overiq/154.md

6.8 KiB
Raw Permalink Blame History

Python 中的breakcontinue语句

原文:https://overiq.com/python-101/break-and-continue-statement-in-python/

最后更新于 2020 年 9 月 21 日


break 语句

break语句用于在满足特定条件时提前终止循环。当在循环体内部遇到break语句时,当前迭代停止,程序控制立即跳转到循环后的语句。break的说法可以写成如下:

break

以下示例演示了 break 语句的作用。

例 1:

蟒蛇 101/第 11 章/break_demo.py

for i in range(1, 10):
    if i == 5:  # when i is 5 exit the loop
        break
    print("i =", i)

print("break out")

现在试试

输出:

i = 1
i = 2
i = 3
i = 4
break out

一旦i的值为5,条件i == 5变为真,break语句导致循环终止,程序控制跳转到 for 循环之后的语句。执行第 6 行的 print 语句,程序结束。

例 2:

以下程序提示用户输入一个数字,并确定输入的数字是否为质数。

蟒蛇 101/第 11 章/prime_or_not.py

num = int(input("Enter a number: "))

is_prime = True

for i in range(2, num):
    if num % i == 0:
        is_prime = False  # number is not prime
        break  # exit from for loop

if is_prime:
    print(num, "is prime")
else:
    print(num, "is not a prime")

现在试试

首次运行输出:

Enter a number: 11
11 is prime

第二次运行输出:

Enter a number: 23
23 is prime

第三次运行输出:

Enter a number: 6
6 is not a prime

质数是只能被1或自身整除的数。以下是质数的一些例子:

1, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 33, 37, 41

如果一个数n不能被从2n-1的任何数整除,那么它就是质数。请考虑以下示例:

例 1:

5 是素数吗?

以下是判断数字 5 是否是质数的步骤。

问题 编程语句 结果
5 能被 2 整除吗? 5 % 2 == 0 False
5 能被 3 整除吗? 5 % 3 == 0 False
5 能被 4 整除吗? 5 % 4 == 0 False

结果:5 是质数

例 2:

9 是素数吗?

以下是判断数字 9 是否是质数的步骤。

问题 编程语句 结果
9 能被 2 整除吗? 9 % 2 == 0 False
9 能被 3 整除吗? 9 % 3 == 0 True

第二步我们的测试9 % 3 == 0通过了。换句话说,9可以被3整除,也就是说9不是素数。在这一点上,用剩余的数字来检验9的可分性是没有意义的。所以我们停下来。

这正是我们在上述程序中所做的。在第 1 行,我们要求用户输入一个数字。在第 3 行,我们已经用布尔值True声明了一个变量is_prime。最后,这个变量将决定用户输入的数字是否是质数。

for 循环迭代通过2num-1。如果num可以被该范围内的任意数字整除(第 6 行),我们将is_prime设置为False,并立即退出 for 循环。但是,如果条件n % i == 0永远不满足break语句将不会执行,is_prime将保持设置为True。在这种情况下num将是一个质数。

嵌套循环中的 break 语句

在嵌套循环中,break语句只终止它出现的循环。例如:

蟒蛇 101/第 11 章/break _ inside _ nested _ loop . py

for i in range(1, 5):    
    print("Outer loop i = ", i, end="\n\n")
    for j in range (65, 75):
        print("\tInner loop chr(j) =", chr(j))
        if chr(j) == 'C':
            print("\tbreaking out of inner for loop ...\n")
            break

    print('-------------------------------------------------')

现在试试

输出:

Outer loop i =  1

        Inner loop chr(j) = A
        Inner loop chr(j) = B
        Inner loop chr(j) = C
        breaking out of inner for loop ...

-------------------------------------------------
Outer loop i =  2

        Inner loop chr(j) = A
        Inner loop chr(j) = B
        Inner loop chr(j) = C
        breaking out of inner for loop ...

-------------------------------------------------
Outer loop i =  3

        Inner loop chr(j) = A
        Inner loop chr(j) = B
        Inner loop chr(j) = C
        breaking out of inner for loop ...

-------------------------------------------------
Outer loop i =  4

        Inner loop chr(j) = A
        Inner loop chr(j) = B
        Inner loop chr(j) = C
        breaking out of inner for loop ...

-------------------------------------------------

对于外部循环的每次迭代,内部 For 循环执行三次。一旦条件chr(j) == 'C'满足break语句,就会立即退出内部 for 循环。然而,外部 for 循环将照常执行。

连续语句

continue语句用于前进到下一个迭代,而不执行循环体中的剩余语句。就像break语句一样,continue语句一般与条件连用。continue语句可以写成如下:

continue

这里有一个例子来演示continue语句的工作原理:

蟒蛇 101/第 11 章/continue_demo.py

for i in range(1, 10):
    if i % 2 != 0:
        continue
    print("i =", i)

现在试试

输出:

i = 2
i = 4
i = 6
i = 8

在上述程序中,当条件i % 2 != 0评估为True时,执行continue语句,省略循环体内print()函数的执行,程序控制前进到循环的下一次迭代。

我们也可以在同一个循环中一起使用breakcontinue语句。例如:

蟒蛇 101/第 11 章/休息和继续

while True:
    value = input("\nEnter a number: ")

    if value == 'q':  # if input is 'q' exit from the while loop
        print("Exiting program (break statement executed)...")
        break

    if not value.isdigit():  # if input is not a digit move on to the next iteration
       print("Enter digits only (continue statement executed)")
       continue

    value = int(value)
    print("Cube of", value, "is", value**3)  # everything is fine, just print the cube

现在试试

输出:

Enter a number: 5
Cube of 5 is 125

Enter a number: 9
Cube of 9 is 729

Enter a number: @#
Enter digits only (continue statement executed)

Enter a number: 11
Cube of 11 is 1331

Enter a number: q
Exiting program (break statement executed)...

上面的程序要求用户输入一个数字并计算它的立方。如果输入了一个数字,程序将显示该数字的立方。如果用户输入非数字字符,则执行continue语句,跳过循环主体中剩余语句的执行,程序再次要求用户输入。另一方面,如果用户输入q,则执行循环体中的break语句while 循环终止。