The table given below differentiates break and continue keyword:
|leaves the loop||jumps for next iteration|
|skips remaining execution of complete loop||skips execution of remaining statement(s) inside the loop for current iteration|
|useful, if condition always evaluates to be True||useful, if wants to skip execution of some statement(s) inside the loop for any particular iteration|
I's sure, after understanding the example program given below, you will get the complete understanding about break Vs. continue keyword in Python. That is, how these two keywords or statements are used in Python programming:
nums = [1, 2, 3, 4, 5] print("----Using \"break\"-------") for n in nums: if n == 3: break print(n) print("----Using \"continue\"-------") for n in nums: if n == 3: continue print(n)
This program produces the output as shown in the snapshot given below:
As you can see from above program, the first block of code, that is:
for n in nums: if n == 3: break print(n)
prints only 1, 2. Because, when the value of n becomes 3, then the condition n == 3 or 3 == 3 evaluates to be True, and using break, the execution of loop gets terminated. Whereas the second part, that is the following block of code:
for n in nums: if n == 3: continue print(n)
prints all the numbers except 3. Because, when the condition n == 3 evaluates to be True, therefore using continue, the program flow jumps to the next iteration of the loop, and the remaining statement(s) after the keyword continue, that is print(n) gets skipped.
© Copyright 2021. All Rights Reserved.