How To Control Python For Loop with Break Statement?


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.

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 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.

for i in range(1,10): 
  print(i) 
  if(i>=5): 
    break
Break For Loop After Given Step
Break For Loop After Given Step

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.

mysum=0 
for i in range(1,10): 
  mysum=mysum+i       
  print(mysum)        
  if(mysum>20):       
    break
Break For Loop After Specified Condition
Break For Loop After Specified Condition

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.

for i in [1,23,34,6,5,79,0]: 
  print(i) 
  if(i==5): 
    break
Break List For Loop
Break List For Loop

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 .

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 
Break Dictionary For Loop 

LEARN MORE  How To Create Nested For Loops In Python?

Leave a Comment