与其他编程语言一样,在python中,break语句用于终止循环的执行。它终止循环的执行并将控制权转移到循环之后编写的语句。
如果另一个循环(嵌套循环)中有一个循环,并且在内部循环中使用break语句–它将中断内部循环的语句并将控制权转移到内部循环之后编写的下一个语句。同样,如果在外部循环的范围内使用break语句–它将中断外部循环的执行,并将控制权转移到在外部循环之后编写的下一个语句。
break语句的语法:
break
示例1:在这里,我们打印从1到10的严重数字,并且如果counter的值等于7,则终止循环。
# 中断语句的python示例 counter = 1 # 循环1到10 # 如果counter == 7终止 while counter<=10: if counter == 7: break print(counter) counter += 1 print("outside of the loop")
输出结果
1 2 3 4 5 6 outside of the loop
示例2:在这里,我们正在打印字符串的字符,如果字符不是字母,则终止字符的打印。
# 中断语句的python示例 string = "NHOOO.Com" # 如果终止循环 # 任何字符都不是字母 for ch in string: if not((ch>='A' and ch<='Z') or (ch>='a' and ch<='z')): break print(ch) print("outside of the loop")
输出结果
I n c l u d e H e l p outside of the loop
示例3:在这里,我们有两个循环,外部循环为“ while True:”,它处理多个输入,内部循环用于打印给定编号的表–输入为0 –内部循环将终止。
# 中断语句的python示例 count = 1 num = 0 choice = 0 while True: # 输入号码 num = int(input("Enter a number: ")) # 如果num为0则中断 if num==0: break # 终止内循环 # 打印表 count = 1 while count<=10: print(num*count) count += 1 # 输入选择 choice = int(input("press 1 to continue...")) if choice != 1: break # 终止外循环 print("bye bye!!!")
输出结果
Enter a number: 21 21 42 63 84 105 126 147 168 189 210 press 1 to continue...1 Enter a number: 23 23 46 69 92 115 138 161 184 207 230 press 1 to continue...0 bye bye!!!