Python教程-Python break 语句

在 Python 中,break 是一个关键字,用于将程序控制从循环中跳出。break 语句逐个中断循环,即在嵌套循环的情况下,它会先中断内部循环,然后继续中断外部循环。换句话说,我们可以说 break 用于终止当前程序的执行,控制流转到循环后的下一行。
通常在需要根据给定条件中断循环的情况下使用 break。下面是在 Python 中使用 break 语句的语法。
语法:
#loop statements
break;
示例 1: 带有 for 循环的 break 语句
代码
# break statement example
my_list = [1, 2, 3, 4]
count = 1
for item in my_list:
if item == 4:
print("Item matched")
count += 1
break
print("Found at location", count)
输出:
Item matched
Found at location 2
在上面的示例中,使用 for 循环迭代一个列表。当项目与值 4 匹配时,执行 break 语句,循环终止。然后通过定位项目来打印计数。
示例 2: 提前跳出循环
代码
# break statement example
my_str = "python"
for char in my_str:
if char == 'o':
break
print(char)
输出:
p
y
t
h
当在字符列表中找到字符时,开始执行 break,迭代立即停止。然后打印语句的下一行被打印出来。
示例 3: 带有 while 循环的 break 语句
代码
# break statement example
i = 0;
while 1:
print(i," ",end=""),
i=i+1;
if i == 10:
break;
print("came out of while loop");
输出:
0 1 2 3 4 5 6 7 8 9 came out of while loop
与上面的程序相同。while 循环初始化为 True,这是一个无限循环。当值为 10 且条件为真时,break 语句将被执行,并通过终止 while 循环跳转到后面的打印语句。
示例 4: 带有嵌套循环的 break 语句
代码
# break statement example
n = 2
while True:
i = 1
while i <= 10:
print("%d X %d = %d\n" % (n, i, n * i))
i += 1
choice = int(input("Do you want to continue printing the table? Press 0 for no: "))
if choice == 0:
print("Exiting the program...")
break
n += 1
print("Program finished successfully.")
输出:
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
Do you want to continue printing the table? Press 0 for no: 1
3 X 1 = 3
3 X 2 = 6
3 X 3 = 9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
Do you want to continue printing the table? Press 0 for no: 0
Exiting the program...
Program finished successfully.
上面的程序中有两个嵌套循环。内部循环负责打印乘法表,而外部循环负责递增 n 的值。当内部循环完成执行后,用户必须继续打印。输入 0 时,最终执行 break 语句,嵌套循环终止。