Loops in Python performs tasks in an efficient manner. But sometimes, there may be some condition where you want to end the execution completely or skip an iteration or ignore that condition. These can be done by loop control statements. Loop control statements are break , continue and pass.
Continue Statement in Python:
It is a loop control statemet.
It forces the loop to execute the next iteration of the loop.
When this statement is used inside the loop , the code icluding the continue statement will be skipped and the next iteration will begin.
The continue statement in Python returns the control to the beginning of the loop.
#continue statement
#it will be print the odd numbers from 1 to 10
for i in range(1,11):
if(i%2==0): #when i%2==0 it will move to next iteration
continue
else:
print(i,end=' ')
Output:
1 3 5 7 9
Break Statement in Python:
It is a loop control statement.
Break statement is used to terminate the loop , if a specific condition arises.
If a break statement is present in the nested loop, then it terminates the loop which contains break statement.
The most common use for break is when some external condition is triggered which requires termination of loop
#break statement
#loop will terminate if a number will divisble by 2 and 3 both
for i in range(1,11):
if(i%2==0 and i%3==0):
print('')
print("Break's here at", i)
break
else:
print(i,end=' ')
Login/Signup to comment