In this article, you will learn to use the break and continue statements to alter the flow of a loop.
In this article, you will learn-
What is the use of break and continue in Python?
In Python, break and continue statements can alter the flow of a normal loop.
Loops repeat over a square of code until the test articulation is bogus, however, in some cases we wish to end the present cycle or even the entire circle without checking test expression.
The break and continue statements are used in these cases.
Python break statement
The break statement terminates the loop containing it. Control of the program streams to the announcement following the body of the loop.
If the break articulation is inside a nested (loop inside another loop), the break statement will terminate the innermost loop.
Syntax of break
Flowchart of break
Flowchart of break statement in Python
Working on the break statement
Example: Python break
# Use of break statement inside the loop for val in "string": if val == "i": break print(val) print("The end")
s t r The end
In this program, we iterate through the “string” sequence. We check if the letter is I, upon which we break from the loop. Hence, we see in our output that all the letters up till I get printed. After that, the loop terminates
Python continue statement
The continue statement is used to skirt the remainder of the code inside a loop for the present iteration only. the loop doesn’t terminate however continues with the next iteration.
Syntax of Continue
Flowchart of continue
Flowchart of continue statement in Python
The working of continue statement in for and while loop is shown below.
How to continue statement works in python
Example: Python continue
# Program to show the use of continue statement inside loops for val in "string": if val == "i": continue print(val) print("The end")
s t r n g The end
This program is the same as the above example except the break statement has been replaced with continue.
We continue with the loop, if the string is i, not executing the rest of the block. Hence, we see in our output that all the letters except i get printed.
Please feel free to give your comment if you face any difficulty here.
For More Latest Articles Click on Below Link