In this article, we will be covering breaking out of loops in Python.
In Python, in order to iterate through a list, we had used FOR loop. Lets assume that we need to stop FOR loop when we found a specific value within loop. To achieve that, "break" keyword within loop causes FOR loop to break. Lets look at syntax of using break in a python for loop:
# course 11:
# breaking loop in Python
x=0
for index in range(5):
x +=1
if(x==2):
print("x reached 2")
break
print(x)
Output of above breaking FOR loop in Python example:
In above Python example, we first declared a variable called x and set it to 0. We declared a surrogate variable called index and called it 5 times with range function in Python (that generates a list in backscene). Each iteration increased value of x by 1. Within loop, we check condition to evalaute, if value is 2, we are breaking loop to tell it not go on further.