A break statement is a jump statement that terminates the execution of a loop and the control is transferred to resume normal execution after the body of the loop.
Example code for break statement:-
for i in range(1, 10): if i == 5: break else: print(i, end=" ")
Output: 1 2 3 4
Explanation: In the above code, the for loop will iterate 10 times, but as soon as the value of i reaches 5, the for loop is terminated, because of the break statement.
Note:- If a break statement is presented in a nested loop it will terminate only the inner loop in which the break statement is presented.
The continue statement works quite similarly to the break statement. Instead of terminating the loop (break statement), the continue statement forces the loop to continue or execute the next iteration. When the continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped and the next iteration of the loop will begin.
Problem Statement: print numbers from 1 to 10 except 5 using continue statement in Python.
for i in range(1, 10): if i == 5: continue else: print(i, end=" ")
Output:- 1 2 3 4 6 7 8 9 10
Explanation:- In the above program, the loop will iterate 10 times but, if i reach 6, then the control is transferred to for loop, because of the continue statement.
Note:- Continue statement only skips the current iteration but the break statement will terminate the entire loop.