What is the difference between break and continue statements in Python?
Question
What is the difference between break and continue statements in Python?
Solution
The break and continue statements in Python are used to alter the flow of a normal loop (like for or while loop).
-
breakstatement: Thebreakstatement in Python terminates the current loop and resumes execution at the next statement, just like the traditional break statement in C. The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. If thebreakstatement is inside a nested loop (loop inside another loop), thebreakstatement will terminate the innermost loop. -
continuestatement: Thecontinuestatement in Python returns the control to the beginning of the current loop. When encountered, the loop starts next iteration without executing the remaining statements in the current iteration. Thecontinuestatement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.
Here is an example to illustrate the difference:
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found a number", num)
In this example, when the number is even, the continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop to start the next iteration. So, "Found a number" is not printed for even numbers.
for num in range(2, 10):
if num == 5:
print("Found number 5")
break
print("Number is", num)
In this example, when the number is 5, the break statement terminates the loop. So, "Number is" is not printed for numbers after 5.
Similar Questions
Differentiate between break and continue statements
Difference between break and continue statement in C
14. What is the difference between break and continue statement in TCL?
Which of the following is True regarding loops in Python?Loops should be ended with keyword "end".No loop can be used to iterate through the elements of strings.Keyword "break" can be used to bring control out of the current loop.Keyword "continue" is used to continue with the remaining statements inside the loop.
I am confused about the use of break and continue. If I want to perform an iteration but stop when a specified condition is met and then continue with the next iteration, do I use break or continue?
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.