In this article, you will learn how to use the break, continue and pass statements when working with loops in Python. We use break, continue statements to alter the loop’s execution in a certain manner.
| Statement | Description |
|---|---|
break | Terminate the current loop. Use the break statement to come out of the loop instantly. |
continue | Skip the current iteration of a loop and move to the next iteration |
pass | Do nothing. Ignore the condition in which it occurred and proceed to run the program as usual |
The break and continue statements are part of a control flow statements that helps you to understand the basics of Python.
Break Statement in Python
The break statement is used inside the loop to exit out of the loop. In Python, when a break statement is encountered inside a loop, the loop is immediately terminated, and the program control transfer to the next statement following the loop.
In simple words, A break keyword terminates the loop containing it. If the break statement is used inside a nested loop (loop inside another loop), it will terminate the innermost loop.
For example, you are searching a specific email inside a file. You started reading a file line by line using a loop. When you found an email, you can stop the loop using the break statement.
We can use Python break statement in both for loop and while loop. It is helpful to terminate the loop as soon as the condition is fulfilled instead of doing the remaining iterations. It reduces execution time.
Syntax of break:
breakCode language: Python (python)