Google News
logo
Python Break and Continue Statement
The most commonly used for break is when some external condition is triggered requiring a hasty exit from a loop. The Python break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop.

If you are using nested loops, the break statement stops the execution of the innermost loop and start executing the next line of code after the block.
Syntax :
while (expression1) :
   statement_1 
   statement_2
   ......
   if expression2 :
   break
Continue Statement
>>> for i in [1,2,3,4,5]:
	if i==4:
		print ("Element found")
		break
	print (i,)

	
1
2
3
Element found
>>> 

Break Statement in while loop

In the following example while loop breaks when the count value is 5. The print statement after the while loop displays the value of num_sum (i.e. 0+1+2+3+4).

>>> num_sum = 0
>>> count = 0
>>> while(count<10):
	num_sum = num_sum + count
	count = count + 1
	if count== 5:
		break
	print("Sum of first ",count,"integers is : ", num_sum)

	
Sum of first  1 integers is :  0
Sum of first  2 integers is :  1
Sum of first  3 integers is :  3
Sum of first  4 integers is :  6
>>> 

Continue Statement :

The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration. The continue statement can be used in both while and for loops.

Break Statement
>>> a = 0
>>> while a<=5:
	a=a+1
	if a%2==0:
		continue
	print (a)
	print ("End of Loop")

	
1
End of Loop
3
End of Loop
5
End of Loop
>>>