Break and Continue in Python

In Python, break and continue are control flow statements used to modify the normal flow of loops (for or while).

break

break statement terminates any type of 'loop' or 'switch case'. The break statement terminates the loop body immediately and passes control to the next statement after the loop.

Syntax
break
Example
n=0
while n<=50:
  print("value of variable n=",num)
  if n==5:
     break
  n=n+1
print("Out of while-loop")
Output
value of variable n=0
value of variable n=1
value of variable n=2
value of variable n=3
value of variable n=4
value of variable n=5
Out of while-loop

continue

In Python Programming, if we want to take control to the beginning of the loop, by passing the statements inside the loop, which have not yet been executed, in this case we use continue. When continue is encountered inside any loop, control automatically passes to the beginning of loop. A continue is usually associated with if Statement.

Syntax
continue
Example
for i in range(0,4):
  if i==4:
      continue
  print(i)
Output
 0 1 2 3 5 6 7 8

Value 4 is missing in the output,because the value of variable i is 4, the program encountered a continue statement, which makes the control to jump at the beginning of the for loop for next iteration, skipping the statements for current iteration.

Difference Between break and continue
S.No break continue

1.

when break is executed, statement following the break are skipped.and causes the loop to be terminated.

When continue gets executed statement following the continue are skipped and causes the loop to continued with the next iteration.

2.

Syntax
break

Syntax
continue

3.

It can be used in switch statement to transfer the control outside the switch.

It cannot be used inside the switch.

4.

Example
for i in range(0,10):
    if(i==3)
        break
    print(i,end=" ")

Example
for i in range(0,10):
    if(i==3)
        continue
    print(i,end=" ")