Python provides for
loops in order to iterate over the given list, dictionary, array, or similar iterable types. During iteration, we may need to break and exit from the loop according to the current condition. In this tutorial, we will look at how to break a python for
loop with break
statement with different examples.
Python提供for
循环以迭代给定的列表,字典,数组或类似的可迭代类型。 在迭代过程中,我们可能需要根据当前条件中断并退出循环。 在本教程中,我们将通过不同的示例介绍如何使用break
语句中断python for
循环。
中断语法 (Break Syntax)
break
statement has very simple syntax where we only use the break
keyword. We generally check for a condition with if-else blocks and then use break
.
break
语句的语法非常简单,我们仅使用break
关键字。 我们通常使用if-else块检查条件,然后使用break
。
break
给定步骤后中断循环 (Break For Loop After Given Step)
We can use break
after a given step count. We will count the steps and then run break at the given count with if condition check. In this example, we have ranges from 1 to 10 but we will break after the 5th step.
给定步数后,我们可以使用break
。 我们将对步骤进行计数,然后使用条件检查以给定的计数运行中断。 在此示例中,我们的范围是1到10,但是在第5步之后我们会中断。
for i in range(1,10):
print(i)
if(i>=5):
break
![Break For Loop After Given Step](https://i-blog.csdnimg.cn/blog_migrate/0e232886d7ff962169e626abb4d33e01.png)
在指定条件后中断循环(Break For Loop After Specified Condition)
Another useful case for breaking for loop is check given condition which can be different and calculated for each step. In this example, we will sum each step i value and check whether the sum is bigger than 20. If it goes beyond 20 we will terminate for a loop.
打破循环的另一个有用情况是检查给定条件,该条件可以不同并针对每个步骤进行计算。 在此示例中,我们将对每个步骤i的值求和,并检查总和是否大于20。如果超过20,我们将终止循环。
mysum=0
for i in range(1,10):
mysum=mysum+i
print(mysum)
if(mysum>20):
break
![Break For Loop After Specified Condition](https://i-blog.csdnimg.cn/blog_migrate/b9000392c2a72b325709a9c7fdb1c42c.png)
中断清单(Break List For Loop)
The list is a very popular data type used in Python programming languages and we will generally use list
types in order to loop and break. In this example, we will loop in a list and break the list loop if the current element is equal to 5.
列表是Python编程语言中非常流行的数据类型,我们通常会使用list
类型来循环和破坏。 在此示例中,我们将循环访问列表,如果当前元素等于5,则中断列表循环。
for i in [1,23,34,6,5,79,0]:
print(i)
if(i==5):
break
![Break List For Loop](https://i-blog.csdnimg.cn/blog_migrate/757089d5deb17a86d0b2442b277200d0.png)
中断字典循环(Break Dictionary For Loop)
Dictionary is another popular type used in Python programming language. We can check the given dictionary current element key and value in order to break for a loop. In this example, we will look current value and break the loop if it is end
.
字典是Python编程语言中使用的另一种流行类型。 我们可以检查给定的字典当前元素的键和值,以便中断循环。 在此示例中,我们将查看当前值,如果为end
则中断循环。
mydict={'a':'This','b':'is','c':'end','d':'but'}
for k,v in mydict.items():
print(v)
if(v=='end'):
break
![Break Dictionary For Loop](https://i-blog.csdnimg.cn/blog_migrate/a98ca9c29dbb107242d171f8469d0c70.png)
翻译自: https://www.poftut.com/control-python-loop-break-statement/