Python break 语句
break 是Python中的关键字,用于将程序控制从循环中退出。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语句开始执行,并且迭代立即停止。然后打印print语句的下一行。
示例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循环跳转到后面的print语句。
示例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语句最终执行,嵌套循环终止。