How to use Python Break & Continue statements?In this short tutorial, we look at how the python break and python continue statements affect the flow of a loop and how you could effectively in your programs.
Table of Contents
- Why do we use python break and other loop control statements?
- Python break statement
- Python continue statement
- Closing thoughts
- Other Related Concepts
Why do we use python break and other loop control statements?Loops in python are used to iterate or repeat a command multiple times. Python further provides few more statements to help us control the flow of the loop. Say you would want to skip a particular iteration or exit the loop when a particular condition is met python lets us perform these operations using the set of inbuilt loop control statements.
In this tutorial, we look at the two most commonly used control statements. Python break and continue.
Python break statementA for loop runs for a set number of iterations and while runs until a condition is true. However, say you need to exit the loop before it ends, this is where the python break statements are used. The break statements are your methods of asking the loop to stop right now and execute the next statement. And almost all such instances are done when a condition is triggered and that is why python break is generally placed inside an if statement.
Note: Although python break exits the loops, it only exits the loop it is placed in, so while using nested loop only the loop containing the break statement would be exited.
The loop runs 5 times and when if is true, the python break statement runs and exits the loop.
Although we used a for loop for our code example it can be used in a while as well. One of the most common use cases of the python break is to look for and exit the loop when the word "exit" is entered.
Python Continue StatementUnlike the python break, the continue statement stops the flow and returns the control to the beginning of the loop. Essentially it does not process the rest of the code for a particular iteration and returns the flow to the start of the code. And similar to the python break, continue is also mostly used inside an if.
As you can see from the output the python continues to skip the iteration for "p" and executes the rest of the code. And similar to the break statement continue can also be used with both for and while loops.