A break statement can be define either inside condition or inside looping statements. If it define without conditional statement, the control exit from the loop in first iteration only.
Break statement with for loop
Break statement in for loop
1 n1 = 1
2 n2 = 5
3
4 for n in range(n1, n2):
5 if n == 4:
6 break
7 print(n)
In the above example, a variables are define with initial values. A for loop continue until the specified range(). If the value of the current iteration become 4, the condition become True and the loop will be terminated from the loop. It prints numbers from 1 to 3 on console.
Break statement with while loop
A while loop continue iterating define block of code until the condition is True. A break statement can also be define inside the the while loop to terminate based on the specified condition.
Break statement with while loop
1 n1 = 1
2
3 while n1 != 5:
4 if n1 == 4:
5 break
6 print(n1)
7 n1 += 1
In the above example, a variable is define with initial value. A while loop is define with condition which continue until the specified condition remain true. Once the condition become False, it gets terminated. A if statement validate whether value of variable n1 become 4, the loop will be terminated from the while loop block by skipping further iteration.
Related options for your search